--------------------------------------------------------------------------------------------------
      name:  <unnamed>
       log:  //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/07_output/logs/2_build_d
> atasets.log
  log type:  text
 opened on:   3 Mar 2024, 11:22:43

.         
.         // list dofiles in alphabetical order (saved in local files) 
.         local files : dir "$do_path/2_build_datasets/" files "*.do"

.         local files: list sort files

.         macro list _files
_files:         "01_address_panel_calc_distances.do"
                "02_a_build_precinct_panel_electoral_outcomes.do"
                "02_b_build_precinct_panel_struc_indicators.do"
                "02_c_build_precinct_panel_migration.do" "03_prep_shapefiles.do"
                "04_prep_conv_keys_ltw18.do" "05_address_panel_convert_to_ltw18.do"
                "06_a_build_polling_place_panel.do" "06_b_calc_distances_bw_pp.do"
                "07_finalize_address_panel_ltw18.do" "08_finalize_precinct_panel_ltw18.do"
                "09_finalize_district_panel.do"

.         // run dofiles
.         foreach f of local files {
  2.                 di "Running: `f'"
  3.                 do "$do_path/2_build_datasets/`f'"
  4.         }
Running: 01_address_panel_calc_distances.do

. /*
> Input: tmp/voter_id_panel.dta [panel of geocoded voter-addresses and Polling locations]
> 
> Output: tmp/panel_wahlen.dta [contains the distance between voters and polling places]
> 
> Main task:
>     > calculate street distance b/w address and assigned polling location in each election
> 
> Note: 
>         > To calculate walking distances, module 'osrmtime' is required; to install follow
>                 the following steps (only for windows): 
> 
>                 1. osrmtime package downloaded from github (https://github.com/christophrust/osr
> mtime),
>                         saved & unzipped in folder: 05_package
>                 2. Downloaded OSRM basemap for 'Oberbayern' from http://download.geofabrik.de/eu
> rope/germany/bayern.html
>                         and saved in folder: 05_package/osrm_basemaps
>                 3. to install, execute:
>                         cd "$project/05_packages/osrmtime_release1.3.3/"
>                         net describe osrmtime.pkg, from("$project/05_packages/osrmtime_release1.
> 3.3/")
>                         net install osrmtime.pkg
>                         net get osrmtime.pkg
>                         shell osrminstall.cmd
>                         cd "$project"
>                 5. prepare basemaps, execute:
>                         osrmprepare, mapfile("$project/05_packages/osrm_basemaps/oberbayern-late
> st.osm.pbf") profile(foot) ///
>                         osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14") 
>                         
> */
. 
. 
. ** PULL: Balanced panel of geocoded voter-addresses and polling locations 
. use "$tmp/voter_id_panel.dta", clear

. 
.         // KEEP vars used for distance calculations only
.         keep voter_id* wl_id lat* lon*

. 
.         // KEEP UNIQUE voter and polling location pairs; (osrmtime does not work with "if")
.         duplicates drop voter_id wl_id, force

Duplicates in terms of voter_id wl_id

(1,089,824 observations deleted)

. 
.         // Calculate walking distance between voter and polling location
.         cd "$project/05_packages/osrmtime_release1.3.3/"
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication\05_packages\osrmtime_release1.3.3

.          osrmtime lat_vote lon_vote lat_wl lon_wl, mapfile("$project/05_packages/osrm_basemap/ob
> erbayern-latest.osrm") ///
>                 osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14")
------------------------------------------------------------
Traveltime and Distance with OSRM

Check for running OSRM: not running!
Starting OSRM           now running!
Calculating:
0%---10%---20%---30%--40%---50%---60%--70%---80%---90%--100%

finished calculation!
------------------------------------------------------------

.         cd "$project"
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication

.         
.         // assert no errors
.         assert return_code==0

.                 
.         // Rename generated variable
.         ren     distance street_dist

.         
.         // Convert walking distance to km & label
.         replace street_dist=street_dist/1000
(266,912 real changes made)

.         lab var street_dist "walking distance in km"

.         
.         // keep pair-identifier and generated distances
.         keep voter_id wl_id street_dist 

. 
.         // merge unique pairs of voter-PP + distances with full voter-address panel
.         merge 1:m voter_id wl_id using "$tmp/voter_id_panel.dta", assert(3) nogen 
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                         1,357,011  
    -----------------------------------------

. 
.         // SAVE: balanced address panel with distances
.         order voter_id voter_id_str wahl_id wahl sb stadtbez

.         isid voter_id wahl_id

.         compress
  (0 bytes saved)

.         save "$tmp/panel_wahlen.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/panel_wahlen.dta not
    found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/panel_wahlen.dta saved

. 
end of do-file
Running: 02_a_build_precinct_panel_electoral_outcomes.do

. /*
> Inputs: raw csv files of precinct-level and district-level electoral outcomes for 8 elections:
>                         > ltw_2013_stimmbezirke_zweitstimmen.csv        [state 2013]
>                         > btw_2013_wahlbezirke_zweitstimmen.csv         [federal 2013]
>                         > euw_2014_wahlbezirke.csv                                      [europea
> n 2014]
>                         > btw_2017_zweitstimmen_wahlbezirke.csv         [federal 2017]
>                         > euw_2019_amtlich_ergebnisdownload.csv         [european 2019]
>                         > srw_endergebnisse_stimmbezirke.csv            [municipal 2014]
>                         > srw_2020_ergebnisdownload.xlsx                        [municipal 2020]
>                         
> Outputs:
>                         > tmp/raw_stimmbez_all_elections          [Precinct-level electoral outc
> omes]
>                         > tmp/stadtbez_postalcomp_partyoutc   [District-level electoral outcomes
> ]
> 
> Tasks:
> A) Read the raw election files containing election outcomes at the precinct level 
>         ("Stimmbezirk"-level) and append into one single file
>         
> Note: Compute % shares of party results as:
>                 municipal elections (city council): #votes/ total #valid votes 
>                 all other elections: #voter/ (#voters - #invalid_votes)
>                 
> B) Compute district-level ("Stadtbezirk"-level) outcomes (overall turnout, share mail-in, party 
> outcomes)
> 
> 
>                                 
> */
. 
. ********************************************************************************
. // A: Read raw election files an Append into single file (polling place voters only) //
. ********************************************************************************
. 
. ****** STEP 1: define programm applicable to each file ******
. 
. * i) Clean Voter info (applicable to all elections)
. cap program drop clean_elections

. program  clean_elections
  1.         
.         missings dropobs, force
  2.         
.         cap rename wahlbezirksart stimmbezirksart // EuE-19
  3.         
. * gen Stimmbezirks-ID and clean ID (strip of 3. digit "Zero")
.         tostring gebietsnummer, gen(stimmbezirk)
  4.         drop     gebietsnummer
  5.         
.         replace         stimmbezirk = "0"+ stimmbezirk if strlen(stimmbezirk) == 4
  6.         replace         stimmbezirk = substr(stimmbezirk,1,2) +substr(stimmbezirk,4,.)
  7.         destring        stimmbezirk, replace
  8.         lab var         stimmbezirk "Stimmbezirk ID (string)"
  9.         
. * rename Variables
.         rename wahlberechtigtegesamt                            wahlber_gesamt
 10.         rename wahlberechtigteohnewahlschein            wahlber_ohne_wahlschein
 11.         rename wahlberechtigtemitwahlschein                     wahlber_mit_wahlschein
 12.         rename wahlberechtigtenichtimwählerv*          wahlber_nicht_im_waehlerv
 13.         rename wählergesamt                                                    waehler_gesamt
 14.         rename wählermitwahlschein                                     waehler_mit_wahlschein
 15.         rename ungültigestimmen                                                ungueltige_sti
> mmen         
 16.         
.         cap rename *ü* *ue*
 17.         cap rename *ä* *ae*
 18. 
. * GEN Variable
.         gen     waehler_ohne_wahlschein =                       waehler_gesamt - waehler_mit_wah
> lschein
 19.         
.  * Lab variables in english     
.         lab var waehler_ohne_wahlschein                         "Voters w/o polling card"
 20.         lab var wahlber_gesamt                                          "Nbr of eligible vote
> rs"
 21.         lab var wahlber_ohne_wahlschein                         "Eligible voters w/o polling 
> card"
 22.         lab var wahlber_mit_wahlschein                          "Eligible voters with polling
>  card"
 23.         lab var wahlber_nicht_im_waehlerv                       "Eligible voters NOT in elect
> oral roll"
 24.         lab var waehler_gesamt                                          "Nbr of voters"
 25.         lab var waehler_mit_wahlschein                          "Eligible voters with polling
>  card"
 26.         lab var ungueltige_stimmen                              "Invalid votes"
 27.         
. 
. end

. 
. * ii) Clean Outcomes 
. cap program drop clean_outcomes1

. program  clean_outcomes1
  1.         
.         
.         // SE-13 FE-13 EuE-14 ME-14
.         cap confirm variable partei
  2.         if !_rc {
  3.                 rename partei                   v1
  4.                 rename anzahlstimmen    v2
  5.                 rename prozentzahl              v3
  6. 
.         
.                 rename v* v#, addnumber
  7. 
.                 forvalues k= 1(3)80 {
  8.                         cap confirm variable v`k'
  9.                         if _rc {
 10.                                 continue
 11.                         }
 12.                         local l = `k' +1
 13.                         local m = `k' +2
 14.                         
.                         sort v`k'
 15.                         assert v`k'[1] == v`k'[_N]
 16.                         local name = v`k'[1]
 17.                         local partei = subinstr("`name'"," / FW FREIE WÄHLER München e.V.", "
> ",.)
 18.                         local partei = subinstr("`partei'","Ü", "UE",.)
 19.                         local partei = subinstr("`partei'","Ö", "OE",.)
 20.                         local partei = subinstr("`partei'","Ä", "AE",.)
 21.                         local partei = subinstr("`partei'","/", "_",.)
 22.                         local partei = lower(subinstr("`partei'",".", "",.))
 23.                         local partei = lower(subinstr("`partei'"," ", "",.))
 24.                         rename v`l' anz_`partei'
 25.                         lab var anz_`partei' "Votes for `name'"
 26.                         
.                 }
 27.         }
 28.         cap drop v* // drop Shares/Party name
 29.         
.         // FE-17 EuE19 SE-18 ME-20
.         cap rename anzahl* anz_=
 30.         cap rename *anzahl* **
 31.         cap drop anteil*
 32.         cap rename *fwmuenchen* **
 33.         
.         // remove Umlaute for all elections
.         cap rename *ö* *oe*
 34.         cap rename *ü* *ue*
 35.         cap rename *ä* *ae*
 36.         
. end

.                         
. 
. 
. ****** STEP 2: Read individual election files (precinct-level variables) ******
. 
. tempfile ergebnis_ltw2013 ergebnis_btw2013 ergebnis_kow2014 ergebnis_euw2014 ///
>                         ergebnis_btw2017 ergebnis_ltw2018 ergebnis_euw2019 ergebnis_kow2020

. 
. 
. * 1) SE-13
.         import delim "$rawdata/election_office/ltw_2013/ltw_2013_stimmbezirke_zweitstimmen.csv",
>  encoding("utf-8") delim(";") varnames(1) clear
(46 vars, 941 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerverz
    wählergesamt wählermitwahlschein ungültigestimmen partei anzahlstimmen prozentzahl v14 v15 v16
    v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39
    v40 v41 v42 v43 v44 v45 v46:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(309 real changes made)
(941 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // gen Election ID
.         gen wahl = "LTW13"

.         // save
.         save `ergebnis_ltw2013'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000001.tmp saved as .dta format

. 
. * 2) FE-13
.         import delim "$rawdata/election_office/btw_2013/btw_2013_wahlbezirke_zweitstimmen.csv", 
> encoding("utf-8") delim(";")  varnames(1) clear
(70 vars, 941 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerverz
    wählergesamt wählermitwahlschein ungültigestimmen partei anzahlstimmen prozentzahl v14 v15 v16
    v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39
    v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 v50 v51 v52 v53 v54 v55 v56 v57 v58 v59 v60 v61 v62
    v63 v64 v65 v66 v67 v68 v69 v70:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(309 real changes made)
(941 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // gen Election ID
.         gen wahl = "BTW13"

.         // save
.         save `ergebnis_btw2013'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000002.tmp saved as .dta format

.         
. 
. * 3) EuE-14
.         import delim "$rawdata/election_office/euw_2014/euw_2014_wahlbezirke.csv", encoding("utf
> -8") delim(";")  varnames(1) clear
(82 vars, 941 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerverz
    wählergesamt wählermitwahlschein ungültigestimmen partei anzahlstimmen prozentzahl v14 v15 v16
    v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39
    v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 v50 v51 v52 v53 v54 v55 v56 v57 v58 v59 v60 v61 v62
    v63 v64 v65 v66 v67 v68 v69 v70 v71 v72 v73 v74 v75 v76 v77 v78 v79 v80 v81 v82:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(309 real changes made)
(941 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // gen Election ID
.         gen wahl = "EUW14"

.         // save
.         save `ergebnis_euw2014'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000004.tmp saved as .dta format

.         
. 
. * 4) FE-17
.         import delim "$rawdata/election_office/btw_2017/btw_2017_zweitstimmen_wahlbezirke.csv", 
> encoding("utf-8") delim(";")  varnames(1) clear
(52 vars, 944 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerverz
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlgrüne anteilgrüne anzahlfdp anteilfdp anzahlafd anteilafd anzahldielinke anteildielinke
    anzahlfreiewähler anteilfreiewähler anzahlpiraten anteilpiraten anzahlödp anteilödp anzahlbp
    anteilbp anzahlnpd anteilnpd anzahltierschutzpartei anteiltierschutzpartei anzahlmlpd
    anteilmlpd anzahlbüso anteilbüso anzahlbge anteilbge anzahldib anteildib anzahldkp anteildkp
    anzahldm anteildm anzahldiepartei anteildiepartei anzahlgesundheitsforschung
    anteilgesundheitsforschung anzahlvpartei anteilvpartei:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(311 real changes made)
(944 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

. 
.         // gen Election ID
.         gen wahl = "BTW17"

.         // save
.         save `ergebnis_btw2017'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000005.tmp saved as .dta format

.         
. * 5) EuE-19
.         import excel "$rawdata/election_office/euw_2019/euw_2019_amtlich_ergebnisdownload.xlsx",
>  clear ///
>                           sheet("WahlbezirkeStimmen") case(lower) firstrow
(90 vars, 620 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer wahlbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlgrüne anteilgrüne anzahlafd anteilafd anzahlfreiewähler anteilfreiewähler anzahlfdp
    anteilfdp anzahldielinke anteildielinke anzahlödp anteilödp anzahlbp anteilbp anzahlpiraten
    anteilpiraten anzahltierschutzpartei anteiltierschutzpartei anzahlnpd anteilnpd
    anzahldiepartei anteildiepartei anzahlfamilie anteilfamilie anzahlvolksabstimmung
    anteilvolksabstimmung anzahldkp anteildkp anzahlmlpd anteilmlpd anzahlsgp anteilsgp
    anzahltierschutzhier anteiltierschutzhier anzahltierschutzallianz anteiltierschutzallianz
    anzahlbündnisc anteilbündnisc anzahlbig anteilbig anzahlbge anteilbge anzahldiedirekte
    anteildiedirekte anzahldiem25 anteildiem25 anzahliiiweg anteiliiiweg anzahldiegrauen
    anteildiegrauen anzahldierechte anteildierechte anzahldievioletten anteildievioletten
    anzahlliebe anteilliebe anzahldiefrauen anteildiefrauen anzahlgrauepanther anteilgrauepanther
    anzahllkr anteillkr anzahlmenschlichewelt anteilmenschlichewelt anzahlnl anteilnl
    anzahlökolinx anteilökolinx anzahldiehumanisten anteildiehumanisten anzahlparteifürdietiere
    anteilparteifürdietiere anzahlgesundheitsforschung anteilgesundheitsforschung anzahlvolt
    anteilvolt:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(203 real changes made)
(620 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // gen Election ID
.         gen wahl = "EUW19"

.         // save
.         save `ergebnis_euw2019'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000007.tmp saved as .dta format

.         
. * 6) SE-18
.         import excel "$rawdata/election_office/ltw_2018/ltw_2018_amtlich_ergebnisdownload.xlsx",
>  clear ///
>                           sheet("StimmbezirkeZweitstimmen") case(lower) firstrow
(44 vars, 956 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlfreiewähler anteilfreiewähler anzahlgrüne anteilgrüne anzahlfdp anteilfdp anzahldielinke
    anteildielinke anzahlbp anteilbp anzahlödp anteilödp anzahlpiraten anteilpiraten anzahlafd
    anteilafd anzahllkr anteillkr anzahlmut anteilmut anzahldiehumanisten anteildiehumanisten
    anzahldiepartei anteildiepartei anzahlgesundheitsforschung anteilgesundheitsforschung
    anzahltierschutzpartei anteiltierschutzpartei anzahlvpartei anteilvpartei:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(313 real changes made)
(956 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // gen Election ID
.         gen wahl = "LTW18"

.         // save
.         save `ergebnis_ltw2018'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000006.tmp saved as .dta format

.         
. * 7) ME-14 (city council "Stadtratswahlen")
.         import delim "$rawdata/election_office/kommw_2014/srw_endergebnisse_stimmbezirke.csv", e
> ncoding("utf-8") delim(";")  varnames(1) clear
(52 vars, 1,024 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerverz
    wählergesamt wählermitwahlschein ungültigestimmen partei anzahlstimmen prozentzahl v14 v15 v16
    v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39
    v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 v50 v51 v52:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(345 real changes made)
(1,024 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // NOTE: SRW include about 80 votes per person => % voting shares obtained by first comp
> uting total #votes
.         egen kow_stimmenges = rowtotal(anz_*)

.         lab var kow_stimmenges "Ges. gültige Stimmen STADTRATSWAHLEN (nur KOW)"

.         // gen Election ID
.         gen wahl = "KOW14"

.         // save
.         save `ergebnis_kow2014'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000003.tmp saved as .dta format

.         
. * 8) ME-20 (city council "Stadtratswahlen")
.         import excel "$rawdata/election_office/kommw_2020/srw_2020_ergebnisdownload.xlsx", clear
>  ///
>                           sheet("StimmbezirkeStimmen") case(lower) firstrow
(44 vars, 756 obs)

.         // run program
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlgrüne anteilgrüne
    anzahlfreiewählerfwmünchen anteilfreiewählerfwmünchen anzahlafd anteilafd anzahlspd anteilspd
    anzahlfdp anteilfdp anzahlödp anteilödp anzahldielinke anteildielinke anzahlrosaliste
    anteilrosaliste anzahlbp anteilbp anzahlbia anteilbia anzahlfair anteilfair anzahlmünchenliste
    anteilmünchenliste anzahlmut anteilmut anzahldiepartei anteildiepartei anzahlvolt anteilvolt
    anzahlzuba anteilzuba:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str5
(258 real changes made)
(756 real changes made)
stimmbezirk: all characters numeric; replaced as int

.         clean_outcomes1

.         // NOTE: SRW include about 80 votes per person => % voting shares obtained by first comp
> uting total #votes
.         egen kow_stimmenges = rowtotal(anz_*)

.         lab var kow_stimmenges "Ges. gültige Stimmen STADTRATSWAHLEN (nur KOW)"

.         // gen Election ID
.         gen wahl = "KOW20"

.         // save
.         save `ergebnis_kow2020'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000008.tmp saved as .dta format

. clear

. 
.         
. ****** STEP 3: Append files & finalize & save ******
.         * append
.         foreach f in "btw2013" "btw2017" "euw2014" "euw2019" "kow2020" "kow2014" "ltw2013" "ltw2
> 018" {
  2.                 append using `ergebnis_`f''
  3.         }
(variable anz_fdp was int, now long to accommodate using data's values)
(variable anz_afd was int, now long to accommodate using data's values)
(variable anz_dielinke was int, now long to accommodate using data's values)
(variable gebietsartschluessel was str4, now str6 to accommodate using data's values)
(variable anz_freiewaehler was int, now long to accommodate using data's values)
(variable anz_oedp was int, now long to accommodate using data's values)
(variable anz_bp was int, now long to accommodate using data's values)
(variable anz_diepartei was int, now long to accommodate using data's values)
(variable anz_volt was int, now long to accommodate using data's values)
(variable anz_piraten was int, now long to accommodate using data's values)

.         order anz_*, last

.         lab var wahl    "Election ID (string)"

.         
.         * gen Stadtbezirk
.         gen stadtbezirk = floor(stimmbezirk/100)

.         lab var stadtbezirk "District ID (Stadtbezirk)"

.         
.         * drop precinct = 9901 (1 obs in EuE-19) => some votes not assignable to precinct
.         drop if stimmbezirk == 9901
(1 observation deleted)

.                 drop if stimmbezirk == 16 // DROP Munich whole city
(14 observations deleted)

. 
.         
.         
.  *** SAVE: in-person + mail-in votes at DISTRICT level
.         *       Note: except for EuE-19 and ME-20, mail voters (Stimmbez-Art = 21) already inclu
> ded here
.         preserve

.                 collapse (sum) wahlber* waehl* ung* anz_* kow_stimmenges, by(wahl stadtbezirk st
> immbezirksart)

.                 save "$tmp/stadtbezirk_outcomes.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbezirk_outcomes.dta
    not found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbezirk_outcomes.dta
    saved

.         restore

.         
.         // KEEP in-person votes + polling card requests
.         keep if stimmbezirksart==11     
(1,692 observations deleted)

.         
.  ***SAVE: PRECINCT-level outcomes
.         save "$tmp/raw_stimmbez_all_elections.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/raw_stimmbez_all_elections.
    > dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/raw_stimmbez_all_elections.
    > dta saved

.         
.         
.         
. 
. ********************************************************************************
. // B:   Prepare district-level electoral outcomes
. ********************************************************************************
. 
. *** STEP 1: Read district-level ("Stadtbezirk") outcomes for ME-20 and EuE-19 ***
.         * Note: Other elections files already include mail-in voters (Gebietsart = 21)
.         
. * ME-20
.         import excel "$rawdata/election_office/kommw_2020/srw_2020_ergebnisdownload.xlsx", clear
>  ///
>                   sheet("StadtbezirkeStimmen") case(lower) firstrow
(45 vars, 134 obs)

. 
.         missings dropvars, force

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlgrüne anteilgrüne
    anzahlfreiewählerfwmünchen anteilfreiewählerfwmünchen anzahlafd anteilafd anzahlspd anteilspd
    anzahlfdp anteilfdp anzahlödp anteilödp anzahldielinke anteildielinke anzahlrosaliste
    anteilrosaliste anzahlbp anteilbp anzahlbia anteilbia anzahlfair anteilfair anzahlmünchenliste
    anteilmünchenliste anzahlmut anteilmut anzahldiepartei anteildiepartei anzahlvolt anteilvolt
    anzahlzuba anteilzuba as:
134 observations with missing values

note: as dropped

.         
.         gen stadtbezirk = gebietsnummer
(56 missing values generated)

.         
.         // clean
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer stimmbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlgrüne anteilgrüne
    anzahlfreiewählerfwmünchen anteilfreiewählerfwmünchen anzahlafd anteilafd anzahlspd anteilspd
    anzahlfdp anteilfdp anzahlödp anteilödp anzahldielinke anteildielinke anzahlrosaliste
    anteilrosaliste anzahlbp anteilbp anzahlbia anteilbia anzahlfair anteilfair anzahlmünchenliste
    anteilmünchenliste anzahlmut anteilmut anzahldiepartei anteildiepartei anzahlvolt anteilvolt
    anzahlzuba anteilzuba stadtbezirk:
56 observations with missing values

(56 observations deleted)
stimmbezirk generated as str3
(0 real changes made)
(3 real changes made)
stimmbezirk: all characters numeric; replaced as byte

.         clean_outcomes1

.         drop stimmbezirk 

.         
.         // NOTE: SRW (city council) include about 80 votes per person => % voting shares obtaine
> d by first computing total #votes
.         egen kow_stimmenges = rowtotal(anz_*)

.         lab var kow_stimmenges "Ges. gültige Stimmen STADTRATSWAHLEN (nur ME)"

.         
.         * keep mail voters
.         keep if stimmbezirksart == 21
(52 observations deleted)

. 
.         drop if stadtbezirk == 162
(1 observation deleted)

. 
.         * gen Election ID
.         gen wahl = "KOW20"

.         
.         * save
.         tempfile kow2020_stadtbez

.         save `kow2020_stadtbez'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_00000a.tmp saved as .dta format

.         
.         
. * EUW 2019
.         import excel "$rawdata/election_office/euw_2019/euw_2019_amtlich_ergebnisdownload.xlsx",
>  clear ///
>                           sheet("StadtbezirkeStimmen") case(lower) firstrow
(90 vars, 137 obs)

.                 
.         missings dropobs, force

Checking missings in gebietsartschlüssel gebietsnummer wahlbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlgrüne anteilgrüne anzahlafd anteilafd anzahlfreiewähler anteilfreiewähler anzahlfdp
    anteilfdp anzahldielinke anteildielinke anzahlödp anteilödp anzahlbp anteilbp anzahlpiraten
    anteilpiraten anzahltierschutzpartei anteiltierschutzpartei anzahlnpd anteilnpd
    anzahldiepartei anteildiepartei anzahlfamilie anteilfamilie anzahlvolksabstimmung
    anteilvolksabstimmung anzahldkp anteildkp anzahlmlpd anteilmlpd anzahlsgp anteilsgp
    anzahltierschutzhier anteiltierschutzhier anzahltierschutzallianz anteiltierschutzallianz
    anzahlbündnisc anteilbündnisc anzahlbig anteilbig anzahlbge anteilbge anzahldiedirekte
    anteildiedirekte anzahldiem25 anteildiem25 anzahliiiweg anteiliiiweg anzahldiegrauen
    anteildiegrauen anzahldierechte anteildierechte anzahldievioletten anteildievioletten
    anzahlliebe anteilliebe anzahldiefrauen anteildiefrauen anzahlgrauepanther anteilgrauepanther
    anzahllkr anteillkr anzahlmenschlichewelt anteilmenschlichewelt anzahlnl anteilnl
    anzahlökolinx anteilökolinx anzahldiehumanisten anteildiehumanisten anzahlparteifürdietiere
    anteilparteifürdietiere anzahlgesundheitsforschung anteilgesundheitsforschung anzahlvolt
    anteilvolt:
56 observations with missing values

(56 observations deleted)

.         missings dropvars, force

Checking missings in gebietsartschlüssel gebietsnummer wahlbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlgrüne anteilgrüne anzahlafd anteilafd anzahlfreiewähler anteilfreiewähler anzahlfdp
    anteilfdp anzahldielinke anteildielinke anzahlödp anteilödp anzahlbp anteilbp anzahlpiraten
    anteilpiraten anzahltierschutzpartei anteiltierschutzpartei anzahlnpd anteilnpd
    anzahldiepartei anteildiepartei anzahlfamilie anteilfamilie anzahlvolksabstimmung
    anteilvolksabstimmung anzahldkp anteildkp anzahlmlpd anteilmlpd anzahlsgp anteilsgp
    anzahltierschutzhier anteiltierschutzhier anzahltierschutzallianz anteiltierschutzallianz
    anzahlbündnisc anteilbündnisc anzahlbig anteilbig anzahlbge anteilbge anzahldiedirekte
    anteildiedirekte anzahldiem25 anteildiem25 anzahliiiweg anteiliiiweg anzahldiegrauen
    anteildiegrauen anzahldierechte anteildierechte anzahldievioletten anteildievioletten
    anzahlliebe anteilliebe anzahldiefrauen anteildiefrauen anzahlgrauepanther anteilgrauepanther
    anzahllkr anteillkr anzahlmenschlichewelt anteilmenschlichewelt anzahlnl anteilnl
    anzahlökolinx anteilökolinx anzahldiehumanisten anteildiehumanisten anzahlparteifürdietiere
    anteilparteifürdietiere anzahlgesundheitsforschung anteilgesundheitsforschung anzahlvolt
    anteilvolt:
0 observations with missing values

note: no variables qualify

.         
.         
.         gen stadtbezirk = gebietsnummer

.         
.         // clean
.         clean_elections

Checking missings in gebietsartschlüssel gebietsnummer wahlbezirksart wahlberechtigtegesamt
    wahlberechtigteohnewahlschein wahlberechtigtemitwahlschein wahlberechtigtenichtimwählerv
    wählergesamt wählermitwahlschein ungültigestimmen anzahlcsu anteilcsu anzahlspd anteilspd
    anzahlgrüne anteilgrüne anzahlafd anteilafd anzahlfreiewähler anteilfreiewähler anzahlfdp
    anteilfdp anzahldielinke anteildielinke anzahlödp anteilödp anzahlbp anteilbp anzahlpiraten
    anteilpiraten anzahltierschutzpartei anteiltierschutzpartei anzahlnpd anteilnpd
    anzahldiepartei anteildiepartei anzahlfamilie anteilfamilie anzahlvolksabstimmung
    anteilvolksabstimmung anzahldkp anteildkp anzahlmlpd anteilmlpd anzahlsgp anteilsgp
    anzahltierschutzhier anteiltierschutzhier anzahltierschutzallianz anteiltierschutzallianz
    anzahlbündnisc anteilbündnisc anzahlbig anteilbig anzahlbge anteilbge anzahldiedirekte
    anteildiedirekte anzahldiem25 anteildiem25 anzahliiiweg anteiliiiweg anzahldiegrauen
    anteildiegrauen anzahldierechte anteildierechte anzahldievioletten anteildievioletten
    anzahlliebe anteilliebe anzahldiefrauen anteildiefrauen anzahlgrauepanther anteilgrauepanther
    anzahllkr anteillkr anzahlmenschlichewelt anteilmenschlichewelt anzahlnl anteilnl
    anzahlökolinx anteilökolinx anzahldiehumanisten anteildiehumanisten anzahlparteifürdietiere
    anteilparteifürdietiere anzahlgesundheitsforschung anteilgesundheitsforschung anzahlvolt
    anteilvolt stadtbezirk:
0 observations with missing values

note: no observations qualify
stimmbezirk generated as str3
(0 real changes made)
(3 real changes made)
stimmbezirk: all characters numeric; replaced as byte

.         clean_outcomes1

.         drop stimmbezirk 

. 
.         * keep mail voters
.         keep if stimmbezirksart == 21
(54 observations deleted)

.                 
.         drop if stadtbezirk == 99
(1 observation deleted)

.         drop if stadtbezirk == 162
(1 observation deleted)

.         
.         * gen Election ID
.         gen wahl = "EUW19"

.         
.         * save
.         tempfile euw2019_stadtbez

.         save `euw2019_stadtbez'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_00000b.tmp saved as .dta format

.         
.         
. /* STEP 2: Append and compute Variables */
. 
.         
.         * Pull: poll and mail-in votes at district level
.         use "$tmp/stadtbezirk_outcomes.dta", clear

.         
.         * append KOW20 and EUW19
.         append using `euw2019_stadtbez'

.         append using `kow2020_stadtbez' 

.         sort wahl stadtbezirk stimmbezirksart

.         lab var wahl    "Election ID (string)"

. 
.         
.         * Gen auxilliary district-level variables
.         // mail-in votes
.         bys wahl stadtbezirk (stimmbezirksart): gen waehler_21 = waehler_gesamt[_N]             
>                                 

.         // eligible voters with polling card
.         bys wahl stadtbezirk (stimmbezirksart): gen wahlber_mit_11 = wahlber_mit_wahlschein[1]  
>                 

.         // poll voters with polling card
.         bys wahl stadtbezirk (stimmbezirksart): gen waehler_mit_11 = waehler_mit_wahlschein[1]  
>                 

.         // poll voters total
.         bys wahl stadtbezirk (stimmbezirksart): gen waehler_ges_11 = waehler_gesamt[1]          
>                         

.         // poll voters w/o polling card
.         bys wahl stadtbezirk (stimmbezirksart): gen waehler_ohne_11 = waehler_ges_11 - waehler_m
> it_11   

.         // eligble voters total
.         bys wahl stadtbezirk (stimmbezirksart): assert wahlber_gesamt[1] != 0

.         bys wahl stadtbezirk (stimmbezirksart): replace wahlber_gesamt = wahlber_gesamt[1] if wa
> hlber_gesamt == 0 
(150 real changes made)

.         
. 
.         * Gen: district-level turnout
.         // gen poll turnout (w/ and w/o polling card)
.         gen sbez_turnout_urne_tot = waehler_ges_11/wahlber_gesamt

.         // gen poll turnout (w/o polling card)
.         gen sbez_turnout_urne_ohne = waehler_ohne_11/wahlber_gesamt

.         // gen poll turnout (w/ polling card)
.         gen sbez_turnout_urne_mit = waehler_mit_11/wahlber_gesamt

.         
.         // gen TURNOUT POSTAL
.         gen sbez_turnout_pos = waehler_21/wahlber_gesamt

.         
.         // gen TURNOUT REQUESTED
.         gen sbez_turnout_pos_req = wahlber_mit_11/wahlber_gesamt

.         
.         // gen TURNOUT TOTAL
.         gen sbez_turnout_tot = sbez_turnout_pos + sbez_turnout_urne_tot

.         
.         cap drop tmp*

.         
.         * Lab variables 
.         lab var sbez_turnout_urne_tot   "Turnout at the polling place (w and w/o PC) (district)"

.         lab var sbez_turnout_urne_mit   "Turnout at the polling place (w PC) (district)"

.         lab var sbez_turnout_urne_ohne  "Turnout at the polling place (w/o PC) (district)"

.         lab var sbez_turnout_pos                "Turnout via mail only (district)"

.         lab var sbez_turnout_tot                "Overall turnout (district)"

.         lab var sbez_turnout_pos_req    "Turnout requested polling card (district)"

.         
.         lab var waehler_ges_11  "Votes at the polling place (w and w/o PC) (district)"

.         lab var waehler_ohne_11 "Votes at the polling place (w/o PC) (district)"

.         lab var waehler_21              "Votes via mail (district)"

.         lab var wahlber_mit_11  "Votes requested polling card (district)"

. 
.         ** GEN TOTAL Party Outcomes (Shares): sbez_shr_`partei'
.         // denominator for ME and other elections
.         bys wahl stadtbezirk: egen tmp_kow_stimmenges = total(kow_stimmenges)   // ME: total val
> id votes

.         bys wahl stadtbezirk: egen tmp_totwaehler = total(waehler_gesamt)               // other
> s: total votes

.         bys wahl stadtbezirk: egen tmp_ung = total(ungueltige_stimmen)                  // other
> s: total invalid votes

.         gen tmp_tot_stimmenges = tmp_totwaehler - tmp_ung                                       
>         // others: total valid votes

.         
.         foreach v of varlist anz_* {
  2.                 local partei = subinstr("`v'","anz_","",.)
  3.                 bys wahl stadtbezirk: egen help = total(`v')            
  4.                 gen     sbez_shr_`partei' = help/tmp_tot_stimmenges if !inlist(wahl, "KOW20",
>  "KOW14")
  5.                 replace sbez_shr_`partei' = help/tmp_kow_stimmenges if inlist(wahl, "KOW20", 
> "KOW14")
  6.                 replace sbez_shr_`partei' = 0 if missing(sbez_shr_`partei')
  7.                 lab var sbez_shr_`partei' "Overall party share of `partei' (district)"
  8.                 drop help
  9. 
.                 bys     wahl stadtbezirk: egen sbez_anz_t`partei' = total(`v')
 10.                 lab var sbez_anz_t`partei' "Votes (total) for `partei' (district)"
 11.                 gen     sbez_anz_u`partei'=`v' if stimmbezirksart==11
 12.                 lab var sbez_anz_u`partei' "Votes (polling place) for `partei' (district)"
 13.                 gen     sbez_anz_p`partei'=`v' if stimmbezirksart==21
 14.                 lab var sbez_anz_p`partei' "Votes (mail-in) for `partei' (district)"
 15.         }
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(200 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(225 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)
(100 missing values generated)
(100 real changes made)
(0 real changes made)
(200 missing values generated)
(250 missing values generated)

.         drop tmp*

. 
.         // check if shares make sense
.         egen tmp = rowtotal(sbez_shr_*)

.         assert inrange(tmp, .99,1.001)

.         drop tmp

.         
.         
.         // copy labels
.         foreach v of varlist * {
  2.                 local `v'l : variable label `v'
  3.         }

.                 
.         collapse sbez_shr_* sbez_turnout* sbez_anz_* waehler_ges_11 waehler_ohne_11  waehler_21 
> wahlber_mit_11, by(stadtbezirk wahl)

.         
.         // re-label                                             
.         foreach v of varlist * {
  2.                 lab var `v' "``v'l'"
  3.         }

.         
.         rename stadtbezirk stadtbez

.         lab var stadtbez "District ID (Stadtbezirk)"

. 
.         
.         * save
.         save "$tmp/stadtbez_postalcomp_partyoutc.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbez_postalcomp_partyou
    > tc.dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbez_postalcomp_partyou
    > tc.dta saved

. 
. 
end of do-file
Running: 02_b_build_precinct_panel_struc_indicators.do

. /*
> 
> Input: 
>         > raw structure indicator files from electoral office
>                 > ltw_2013_stimmbezirke_strukturindikatoren_wahlatlas.csv       [state 2013]
>                 > btw_2013_wahlbezirke_strukturindikatoren_wahlatlas.csv        [federal 2013]
>                 > euw_2014_strukturindikatoren_wahlbezirke.csv                          [europea
> n 2014]
>                 > btw_2017_wahlbezirke_strukturindikatoren.csv                          [federal
>  2017]
>                 > euw_2019_strukturindikatoren.xlsx                                             
>         [european 2019]
>                 > ltw_2018_strukturindikatoren.xlsx                                             
>         [state 2018]
>                 > strukturindikatoren_daten_stimmbezirke.csv                            [municip
> al 2014]
>                 > baw_2020_Strukturindikatoren.xlsx                                             
>         [municipal 2020]
>         > $tmp/raw_stimmbez_all_elections.dta [election outcomes precinct-level]
>         
> output file: $tmp/raw_stimmbez_full.dta
> 
> Tasks:
>         > Read the Strukturindikatoren at precinct level, clean, and append to panel.
>         > Merge with election outcomes at precinct level (raw_stimmbez_all_elections)
>  
> Note:
>         * Most struc.indicators are in shares => they are converted to levels to convert them la
> ter on
>                 
> */
. 
. 
. *** STEP 1: define program applicable to each file ***
. 
. cap program drop clean_strucind

. program  clean_strucind
  1.         
.         missings dropobs, force
  2.         missings dropvars, force
  3.         
.         cap rename wahlbezirk           stimmbezirk
  4.         cap rename gebietsnummer        stimmbezirk
  5.         
.         tostring stimmbezirk, replace
  6.         drop if stimmbezirk == "Summe"
  7.         
.         // assert stimmbezirk (precinct) is numerical only
.         gen tmp = real(stimmbezirk)
  8.         assert !missing(tmp)
  9.         drop tmp*
 10.         
. * gen Stimmbezirks-ID and strip of 3. digit "zero"      
.         replace         stimmbezirk = "0"+ stimmbezirk if strlen(stimmbezirk) == 4
 11.         replace         stimmbezirk = substr(stimmbezirk,1,2) +substr(stimmbezirk,4,.)
 12.         destring        stimmbezirk, replace
 13.         lab var         stimmbezirk "Stimmbezirk ID (string) = precinct"
 14.         
.         ds stimmbezirk, not
 15.         foreach v in `r(varlist)' {
 16.                  cap replace `v' = subinstr(`v', ",",".",.)
 17.                 
.         }
 18.          cap drop svbesch
 19.          cap drop erwerbs
 20.          cap drop gebietsart
 21.          cap drop arbeitslos
 22.          cap drop algii
 23. * rename
. cap {
 24.         rename einwohner_innen_insgesamt                        ew_ges
 25.         rename deutsche                                                         ew_dt
 26.         rename eu_auslaender_innen                                      ew_ausl_eu
 27.         rename nicht_eu_auslaender_innen                        ew_ausl_else
 28.         rename einwohner_innen_nach_migrationsh         ew_mihi
 29.         rename einwohner_innen_mit_familienstan         ew_ledig
 30.         rename v8                                                                       ew_ma
> rried
 31.         rename wahlberechtigte_alter_18_bis_24_         wb_18t24
 32.         rename wahlberechtigte_alter_25_bis_34_         wb_25t34
 33.         rename wahlberechtigte_alter_35_bis_44j         wb_35t44
 34.         rename wahlberechtigte_alter_45_bis_59_         wb_45t59
 35.         rename wahlberechtigte_alter_60_jahre_u         wb_60plus
 36.         rename einpersonenhaushalte                             hh_sgl
 37.         rename haushalte_mit_kindern                            hh_kids
 38.         rename wohndauer_in_muenchen                            avg_dur
 39. }
 40. cap {
 41.         rename einwohner_inneninsgesamt                         ew_ges
 42.         rename einwohner_innendeutsche                          ew_dt
 43.         rename einwohner_inneneuauslaenderinnen         ew_ausl_eu
 44.         rename einwohner_innennichteuauslaender         ew_ausl_else
 45.         rename einwohner_innenmigrationshinterg         ew_mihi
 46.         rename einwohner_innenfamilienstandledi         ew_ledig
 47.         rename einwohner_innenfamilienstandverh         ew_married
 48.                 
.         rename wahlberechtigtedeutsche                          wb_dt           // EuE-specific
 49.         rename wahlberechtigteeuauslaender_inne         wb_ausl         // EuE-specific
 50.         
.         rename wahlberechtigtealter1824jahre            wb_18t24
 51.         rename wahlberechtigtealter2534jahre            wb_25t34
 52.         rename wahlberechtigtealter3544jahre            wb_35t44
 53.         rename wahlberechtigtealter4559jahre            wb_45t59
 54.         rename wahlberechtigtealter60jahreundae         wb_60plus
 55.         rename einpersonenhaushalte                             hh_sgl
 56.         rename haushaltemitkindern                                      hh_kids
 57.         rename wohndauerinmuenchen                                      avg_dur
 58. }
 59. cap {
 60.         rename anzahleinwohner                                          ew_ges
 61.         rename anteildeutsche                                           ew_dt
 62.         rename anteileuausländer                                       ew_ausl_eu
 63.         rename anteilnichteuausländer                          ew_ausl_else
 64.         rename anteilmigrationshintergrund                      ew_mihi
 65.         rename anteilledige                                                     ew_ledig
 66.         rename anteilverheiratete                                       ew_married
 67.                 
.         cap rename anteildeutschew                                      wb_dt           // EuE-s
> pecific
 68.         cap rename anteileuausländerw                          wb_ausl         // EuE-specifi
> c
 69.         
.         rename anteil1824jährige*                                      wb_18t24
 70.         rename anteil2534jährige*                                      wb_25t34
 71.         rename anteil3544jährige*                                      wb_35t44
 72.         rename anteil4559jährige*                                      wb_45t59
 73.         rename anteil60jährigeundältere*                      wb_60plus
 74.         rename anteileinpersonenhaushalten                      hh_sgl
 75.         rename anteilhaushaltemitkindern                        hh_kids
 76.         rename wohndauerinmünchen                                      avg_dur
 77. }
 78. cap {
 79.         rename einwohnerinneninsgesamt                          ew_ges
 80.         rename einwohnerinnendeutsche                           ew_dt
 81.         rename einwohnerinneneuausländerinnen          ew_ausl_eu
 82.         rename einwohnerinnennichteuausländerin                ew_ausl_else
 83.         rename einwohnerinnenmigrationshintergr         ew_mihi
 84.         rename einwohnerinnenfamilienstandledig         ew_ledig
 85.         rename einwohnerinnenfamilienstandverhe         ew_married
 86.                 
.         cap rename wahlberechtigtedeutsche                      wb_dt           // EuE-specific
 87.         cap rename wahlberechtigteeuausländerinnen     wb_ausl         // EuE-specific
 88.         
.         rename wahlberechtigtealter1824jahre            wb_18t24
 89.         rename wahlberechtigtealter2534jahre            wb_25t34
 90.         rename wahlberechtigtealter3544jahre            wb_35t44
 91.         rename wahlberechtigtealter4559jahre            wb_45t59
 92.         rename wahlberechtigtealter60jahreundäl        wb_60plus
 93.         rename einpersonenhaushalte                             hh_sgl
 94.         rename haushaltemitkindern                                      hh_kids
 95.         rename wohndauerinmünchen                                      avg_dur
 96. }
 97.                                 
.                
. * In some years shares vs. percentages => convert to percentages
.         foreach v of varlist ew_* wb_* hh_sgl hh_kids {
 98.                 qui su `v'
 99.                 replace `v' = 100*`v' if r(max)<= 1
100.         }
101.         destring *, replace
102. end

.                 
. 
. 
. *** STEP 2: Read and clean individual structural indicator files (precinct-level variables) ***
. 
. tempfile structurind_ltw2013 structurind_btw2013 structurind_kow2014 structurind_euw2014 ///
>                         structurind_btw2017 structurind_ltw2018 structurind_euw2019 structurind_
> kow2020

. 
. * 1) SE-13
.         import delim "$rawdata/election_office/ltw_2013/ltw_2013_stimmbezirke_strukturindikatore
> n_wahlatlas.csv", encoding("utf-8")  varnames(1) clear
(16 vars, 703 obs)

.         // run program
.         clean_strucind

Checking missings in stimmbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
1 observation with missing values

note: no observations qualify

Checking missings in stimmbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
1 observation with missing values

note: no variables qualify
stimmbezirk already string; no replace
(1 observation deleted)
(230 real changes made)
(702 real changes made)
stimmbezirk: all characters numeric; replaced as int
einwohner_~t  nicht_eu_a~n  v8            wahlbere~44j  einpersone~e
deutsche      einwohner_~h  wahlbere~24_  wahlbere~59_  haushalte_~n
eu_auslaen~n  einwohner_~n  wahlbere~34_  wahlberech~u  wohndauer_~n
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_eu: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_else: all characters numeric; replaced as double
(1 missing value generated)
ew_mihi: all characters numeric; replaced as double
(1 missing value generated)
ew_ledig: all characters numeric; replaced as double
(1 missing value generated)
ew_married: all characters numeric; replaced as double
(1 missing value generated)
wb_18t24: all characters numeric; replaced as double
(1 missing value generated)
wb_25t34: all characters numeric; replaced as double
(1 missing value generated)
wb_35t44: all characters numeric; replaced as double
(1 missing value generated)
wb_45t59: all characters numeric; replaced as double
(1 missing value generated)
wb_60plus: all characters numeric; replaced as double
(1 missing value generated)
hh_sgl: all characters numeric; replaced as double
(1 missing value generated)
hh_kids: all characters numeric; replaced as double
(1 missing value generated)
avg_dur: all characters numeric; replaced as double
(1 missing value generated)

.         // gen Election ID
.         gen wahl = "LTW13"

.         // save
.         save `structurind_ltw2013'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000001.tmp saved as .dta format

. 
. * 2) FE-13
.         import delim "$rawdata/election_office/btw_2013/btw_2013_wahlbezirke_strukturindikatoren
> _wahlatlas.csv", encoding("utf-8")  varnames(1) clear
(16 vars, 703 obs)

.         // run program
.         clean_strucind

Checking missings in wahlbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
1 observation with missing values

note: no observations qualify

Checking missings in wahlbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
1 observation with missing values

note: no variables qualify
stimmbezirk already string; no replace
(1 observation deleted)
(230 real changes made)
(702 real changes made)
stimmbezirk: all characters numeric; replaced as int
einwohner_~t  nicht_eu_a~n  v8            wahlbere~44j  einpersone~e
deutsche      einwohner_~h  wahlbere~24_  wahlbere~59_  haushalte_~n
eu_auslaen~n  einwohner_~n  wahlbere~34_  wahlberech~u  wohndauer_~n
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_eu: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_else: all characters numeric; replaced as double
(1 missing value generated)
ew_mihi: all characters numeric; replaced as double
(1 missing value generated)
ew_ledig: all characters numeric; replaced as double
(1 missing value generated)
ew_married: all characters numeric; replaced as double
(1 missing value generated)
wb_18t24: all characters numeric; replaced as double
(1 missing value generated)
wb_25t34: all characters numeric; replaced as double
(1 missing value generated)
wb_35t44: all characters numeric; replaced as double
(1 missing value generated)
wb_45t59: all characters numeric; replaced as double
(1 missing value generated)
wb_60plus: all characters numeric; replaced as double
(1 missing value generated)
hh_sgl: all characters numeric; replaced as double
(1 missing value generated)
hh_kids: all characters numeric; replaced as double
(1 missing value generated)
avg_dur: all characters numeric; replaced as double
(1 missing value generated)

.         // gen Election ID
.         gen wahl = "BTW13"

.         // save
.         save `structurind_btw2013'      
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000002.tmp saved as .dta format

. 
. * 3) EuE-14
.         import delim "$rawdata/election_office/euw_2014/euw_2014_strukturindikatoren_wahlbezirke
> .csv", encoding("utf-8")  varnames(1) clear
(18 vars, 704 obs)

.         // run program
.         clean_strucind

Checking missings in wahlbezirk einwohner_inneninsgesamt einwohner_innendeutsche
    einwohner_inneneuauslaenderinnen einwohner_innennichteuauslaender
    einwohner_innenmigrationshinterg einwohner_innenfamilienstandledi
    einwohner_innenfamilienstandverh wahlberechtigtedeutsche wahlberechtigteeuauslaender_inne
    wahlberechtigtealter1824jahre wahlberechtigtealter2534jahre wahlberechtigtealter3544jahre
    wahlberechtigtealter4559jahre wahlberechtigtealter60jahreundae einpersonenhaushalte
    haushaltemitkindern wohndauerinmuenchen:
1 observation with missing values

note: no observations qualify

Checking missings in wahlbezirk einwohner_inneninsgesamt einwohner_innendeutsche
    einwohner_inneneuauslaenderinnen einwohner_innennichteuauslaender
    einwohner_innenmigrationshinterg einwohner_innenfamilienstandledi
    einwohner_innenfamilienstandverh wahlberechtigtedeutsche wahlberechtigteeuauslaender_inne
    wahlberechtigtealter1824jahre wahlberechtigtealter2534jahre wahlberechtigtealter3544jahre
    wahlberechtigtealter4559jahre wahlberechtigtealter60jahreundae einpersonenhaushalte
    haushaltemitkindern wohndauerinmuenchen:
1 observation with missing values

note: no variables qualify
stimmbezirk already string; no replace
(1 observation deleted)
(230 real changes made)
(703 real changes made)
stimmbezirk: all characters numeric; replaced as int
einwohner_~t  einwohner_~r  einwohner_~h  wahl~24jahre  wahlb~9jahre  haushaltem~n
einwohner_~e  einwohner_~g  wahlberec~he  wahl~34jahre  wahlberec~ae  wohndaueri~n
einwohner_~n  einwohner_~i  wahlberec~ne  wahl~44jahre  einpersone~e
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_eu: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_else: all characters numeric; replaced as double
(1 missing value generated)
ew_mihi: all characters numeric; replaced as double
(1 missing value generated)
ew_ledig: all characters numeric; replaced as double
(1 missing value generated)
ew_married: all characters numeric; replaced as double
(1 missing value generated)
wb_dt: all characters numeric; replaced as double
(1 missing value generated)
wb_ausl: all characters numeric; replaced as double
(1 missing value generated)
wb_18t24: all characters numeric; replaced as double
(1 missing value generated)
wb_25t34: all characters numeric; replaced as double
(1 missing value generated)
wb_35t44: all characters numeric; replaced as double
(1 missing value generated)
wb_45t59: all characters numeric; replaced as double
(1 missing value generated)
wb_60plus: all characters numeric; replaced as double
(1 missing value generated)
hh_sgl: all characters numeric; replaced as double
(1 missing value generated)
hh_kids: all characters numeric; replaced as double
(1 missing value generated)
avg_dur: all characters numeric; replaced as double
(1 missing value generated)

.         // gen Election ID
.         gen wahl = "EUW14"

.         // save
.         save `structurind_euw2014'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000004.tmp saved as .dta format

.         
. 
. * 4) FE-17
.         import delim "$rawdata/election_office/btw_2017/btw_2017_wahlbezirke_strukturindikatoren
> .csv", encoding("utf-8")  varnames(1) clear
(16 vars, 943 obs)

.         // run program
.         clean_strucind

Checking missings in wahlbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
0 observations with missing values

note: no observations qualify

Checking missings in wahlbezirk einwohner_innen_insgesamt deutsche eu_auslaender_innen
    nicht_eu_auslaender_innen einwohner_innen_nach_migrationsh einwohner_innen_mit_familienstan v8
    wahlberechtigte_alter_18_bis_24_ wahlberechtigte_alter_25_bis_34_
    wahlberechtigte_alter_35_bis_44j wahlberechtigte_alter_45_bis_59_
    wahlberechtigte_alter_60_jahre_u einpersonenhaushalte haushalte_mit_kindern
    wohndauer_in_muenchen:
0 observations with missing values

note: no variables qualify
stimmbezirk already string; no replace
(1 observation deleted)
(311 real changes made)
(942 real changes made)
stimmbezirk: all characters numeric; replaced as int
einwohner_~t  nicht_eu_a~n  v8            wahlbere~44j  einpersone~e
deutsche      einwohner_~h  wahlbere~24_  wahlbere~59_  haushalte_~n
eu_auslaen~n  einwohner_~n  wahlbere~34_  wahlberech~u  wohndauer_~n
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt: all characters numeric; replaced as double
ew_ausl_eu: all characters numeric; replaced as double
ew_ausl_else: all characters numeric; replaced as double
ew_mihi: all characters numeric; replaced as double
ew_ledig: all characters numeric; replaced as double
ew_married: all characters numeric; replaced as double
wb_18t24: all characters numeric; replaced as double
wb_25t34: all characters numeric; replaced as double
wb_35t44: all characters numeric; replaced as double
wb_45t59: all characters numeric; replaced as double
wb_60plus: all characters numeric; replaced as double
hh_sgl: all characters numeric; replaced as double
hh_kids: all characters numeric; replaced as double
avg_dur: all characters numeric; replaced as double

.         // gen Election ID
.         gen wahl = "BTW17"

.         // save
.         save `structurind_btw2017'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000005.tmp saved as .dta format

.         
. * 5) EuE-19
.         import excel "$rawdata/election_office/euw_2019/euw_2019_strukturindikatoren.xlsx", clea
> r ///
>                           sheet("WahlbezirkeStrukturdaten") case(lower) firstrow
(22 vars, 619 obs)

.         // run program
.         clean_strucind

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteildeutschew anteileuausländerw anteil1824jährige anteil2534jährige
    anteil3544jährige anteil4559jährige anteil60jährigeundältere anteileinpersonenhaushalten
    anteilhaushaltemitkindern wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte
    erwerbsfähigeleistungsberechtig:
0 observations with missing values

note: no observations qualify

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteildeutschew anteileuausländerw anteil1824jährige anteil2534jährige
    anteil3544jährige anteil4559jährige anteil60jährigeundältere anteileinpersonenhaushalten
    anteilhaushaltemitkindern wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte
    erwerbsfähigeleistungsberechtig:
0 observations with missing values

note: no variables qualify
stimmbezirk was int now str5
(0 observations deleted)
(203 real changes made)
(619 real changes made)
stimmbezirk: all characters numeric; replaced as int
gebietsart~l   anteilnich~r   anteildeut~w   anteil3544~e   anteilhaus~n   erwerbsfäh~g
anzahleinw~r   anteilmigr~d   anteileuau~w   anteil4559~e   wohndaueri~n
anteildeut~e   anteilledige   anteil1824~e   anteil60jä~e   svbeschäft~e
anteileuau~r   anteilverh~e   anteil2534~e   anteileinp~n   arbeitslos~e
(0 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
gebietsartschlüssel: contains nonnumeric characters; no replace
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt already numeric; no replace
ew_ausl_eu already numeric; no replace
ew_ausl_else already numeric; no replace
ew_mihi already numeric; no replace
ew_ledig already numeric; no replace
ew_married already numeric; no replace
wb_dt already numeric; no replace
wb_ausl already numeric; no replace
wb_18t24 already numeric; no replace
wb_25t34 already numeric; no replace
wb_35t44 already numeric; no replace
wb_45t59 already numeric; no replace
wb_60plus already numeric; no replace
hh_sgl already numeric; no replace
hh_kids already numeric; no replace
avg_dur already numeric; no replace
svbeschäftigtendichte: contains nonnumeric characters; no replace
arbeitslosendichte: contains nonnumeric characters; no replace
erwerbsfähigeleistungsberechtig: contains nonnumeric characters; no replace

.         drop gebietsartschlüssel svbeschäftigtendichte arbeitslosendichte erwerbsfähigeleistungs
> berechtig

.         // gen Election ID
.         gen wahl = "EUW19"

.         // save
.         save `structurind_euw2019'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000007.tmp saved as .dta format

.         
. * 6) SE-18
.         import excel "$rawdata/election_office/ltw_2018/ltw_2018_strukturindikatoren.xlsx", clea
> r ///
>                           sheet("StimmbezirkeStrukturdaten") case(lower) firstrow
(20 vars, 619 obs)

.         // run program
.         clean_strucind

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteil1824jährige anteil2534jährige anteil3544jährige anteil4559jährige
    anteil60jährigeundältere anteileinpersonenhaushalten anteilhaushaltemitkindern
    wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte algiiempfängerdichte:
0 observations with missing values

note: no observations qualify

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteil1824jährige anteil2534jährige anteil3544jährige anteil4559jährige
    anteil60jährigeundältere anteileinpersonenhaushalten anteilhaushaltemitkindern
    wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte algiiempfängerdichte:
0 observations with missing values

note: no variables qualify
stimmbezirk was int now str5
(0 observations deleted)
(203 real changes made)
(619 real changes made)
stimmbezirk: all characters numeric; replaced as int
gebietsart~l   anteilnich~r   anteil1824~e   anteil60jä~e   svbeschäft~e
anzahleinw~r   anteilmigr~d   anteil2534~e   anteileinp~n   arbeitslos~e
anteildeut~e   anteilledige   anteil3544~e   anteilhaus~n   algiiempfä~e
anteileuau~r   anteilverh~e   anteil4559~e   wohndaueri~n
(0 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
(619 real changes made)
gebietsartschlüssel: contains nonnumeric characters; no replace
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt already numeric; no replace
ew_ausl_eu already numeric; no replace
ew_ausl_else already numeric; no replace
ew_mihi already numeric; no replace
ew_ledig already numeric; no replace
ew_married already numeric; no replace
wb_18t24 already numeric; no replace
wb_25t34 already numeric; no replace
wb_35t44 already numeric; no replace
wb_45t59 already numeric; no replace
wb_60plus already numeric; no replace
hh_sgl already numeric; no replace
hh_kids already numeric; no replace
avg_dur already numeric; no replace
svbeschäftigtendichte: contains nonnumeric characters; no replace
arbeitslosendichte: contains nonnumeric characters; no replace
algiiempfängerdichte: contains nonnumeric characters; no replace

.         drop svbeschäftigtendichte arbeitslosendichte algiiempfängerdichte gebietsartschlüssel

.         // gen Election ID
.         gen wahl = "LTW18"

.         // save
.         save `structurind_ltw2018'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000006.tmp saved as .dta format

.         
. * 7) ME-14
.         import delim "$rawdata/election_office/kommw_2014/strukturindikatoren_daten_stimmbezirke
> .csv", encoding("utf-8")  varnames(1) clear
(18 vars, 704 obs)

.         // run program
.         clean_strucind

Checking missings in stimmbezirk einwohnerinneninsgesamt einwohnerinnendeutsche
    einwohnerinneneuausländerinnen einwohnerinnennichteuausländerin
    einwohnerinnenmigrationshintergr einwohnerinnenfamilienstandledig
    einwohnerinnenfamilienstandverhe wahlberechtigtedeutsche wahlberechtigteeuausländerinnen
    wahlberechtigtealter1824jahre wahlberechtigtealter2534jahre wahlberechtigtealter3544jahre
    wahlberechtigtealter4559jahre wahlberechtigtealter60jahreundäl einpersonenhaushalte
    haushaltemitkindern wohndauerinmünchen:
1 observation with missing values

note: no observations qualify

Checking missings in stimmbezirk einwohnerinneninsgesamt einwohnerinnendeutsche
    einwohnerinneneuausländerinnen einwohnerinnennichteuausländerin
    einwohnerinnenmigrationshintergr einwohnerinnenfamilienstandledig
    einwohnerinnenfamilienstandverhe wahlberechtigtedeutsche wahlberechtigteeuausländerinnen
    wahlberechtigtealter1824jahre wahlberechtigtealter2534jahre wahlberechtigtealter3544jahre
    wahlberechtigtealter4559jahre wahlberechtigtealter60jahreundäl einpersonenhaushalte
    haushaltemitkindern wohndauerinmünchen:
1 observation with missing values

note: no variables qualify
stimmbezirk already string; no replace
(1 observation deleted)
(230 real changes made)
(703 real changes made)
stimmbezirk: all characters numeric; replaced as int
einwohneri~t  einwohner~in  einwohne~rhe  wahl~24jahre  wahlb~9jahre  haushaltem~n
einwohne~che  einwohneri~r  wahlberec~he  wahl~34jahre  wahlberech~l  wohndaueri~n
einwohner~en  einwohneri~g  wahlberech~n  wahl~44jahre  einpersone~e
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_eu: all characters numeric; replaced as double
(1 missing value generated)
ew_ausl_else: all characters numeric; replaced as double
(1 missing value generated)
ew_mihi: all characters numeric; replaced as double
(1 missing value generated)
ew_ledig: all characters numeric; replaced as double
(1 missing value generated)
ew_married: all characters numeric; replaced as double
(1 missing value generated)
wb_dt: all characters numeric; replaced as double
(1 missing value generated)
wb_ausl: all characters numeric; replaced as double
(1 missing value generated)
wb_18t24: all characters numeric; replaced as double
(1 missing value generated)
wb_25t34: all characters numeric; replaced as double
(1 missing value generated)
wb_35t44: all characters numeric; replaced as double
(1 missing value generated)
wb_45t59: all characters numeric; replaced as double
(1 missing value generated)
wb_60plus: all characters numeric; replaced as double
(1 missing value generated)
hh_sgl: all characters numeric; replaced as double
(1 missing value generated)
hh_kids: all characters numeric; replaced as double
(1 missing value generated)
avg_dur: all characters numeric; replaced as double
(1 missing value generated)

.         // gen Election ID
.         gen wahl = "KOW14"

.         // save
.         save `structurind_kow2014'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000003.tmp saved as .dta format

.         
. * 8) ME-20
.         import excel "$rawdata/election_office/kommw_2020/baw_2020_Strukturindikatoren.xlsx", cl
> ear ///
>                           sheet("StimmbezirkeStrukturdaten") case(lower) firstrow
(22 vars, 756 obs)

.         // run program
.         clean_strucind

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteildeutschew anteileuausländerw anteil1824jährigew anteil2534jährigew
    anteil3544jährigew anteil4559jährigew anteil60jährigeundälterew anteileinpersonenhaushalten
    anteilhaushaltemitkindern wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte
    erwerbsfähigeleistungsberechtig:
0 observations with missing values

note: no observations qualify

Checking missings in gebietsartschlüssel gebietsnummer anzahleinwohner anteildeutsche
    anteileuausländer anteilnichteuausländer anteilmigrationshintergrund anteilledige
    anteilverheiratete anteildeutschew anteileuausländerw anteil1824jährigew anteil2534jährigew
    anteil3544jährigew anteil4559jährigew anteil60jährigeundälterew anteileinpersonenhaushalten
    anteilhaushaltemitkindern wohndauerinmünchen svbeschäftigtendichte arbeitslosendichte
    erwerbsfähigeleistungsberechtig:
0 observations with missing values

note: no variables qualify
stimmbezirk was int now str5
(0 observations deleted)
(258 real changes made)
(756 real changes made)
stimmbezirk: all characters numeric; replaced as int
gebietsart~l   anteilnich~r   anteildeut~w   anteil3544~w   anteilhaus~n   erwerbsfäh~g
anzahleinw~r   anteilmigr~d   anteileuau~w   anteil4559~w   wohndaueri~n
anteildeut~e   anteilledige   anteil1824~w   anteil60jä~w   svbeschäft~e
anteileuau~r   anteilverh~e   anteil2534~w   anteileinp~n   arbeitslos~e
(0 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
(756 real changes made)
gebietsartschlüssel: contains nonnumeric characters; no replace
stimmbezirk already numeric; no replace
ew_ges already numeric; no replace
ew_dt already numeric; no replace
ew_ausl_eu already numeric; no replace
ew_ausl_else already numeric; no replace
ew_mihi already numeric; no replace
ew_ledig already numeric; no replace
ew_married already numeric; no replace
wb_dt already numeric; no replace
wb_ausl already numeric; no replace
wb_18t24 already numeric; no replace
wb_25t34 already numeric; no replace
wb_35t44 already numeric; no replace
wb_45t59 already numeric; no replace
wb_60plus already numeric; no replace
hh_sgl already numeric; no replace
hh_kids already numeric; no replace
avg_dur already numeric; no replace
svbeschäftigtendichte: contains nonnumeric characters; no replace
arbeitslosendichte: contains nonnumeric characters; no replace
erwerbsfähigeleistungsberechtig: contains nonnumeric characters; no replace

.         drop svbeschäftigtendichte arbeitslosendichte erwerbsfähigeleistungsberechtig gebietsart
> schlüssel

.         // gen Election ID
.         gen wahl = "KOW20"

.         // save
.         save `structurind_kow2020'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000008.tmp saved as .dta format

. clear

.         
.         
. *** STEP 3: Append files & MERGE w/ election outcomes ***
.         * append
.         foreach f in "btw2013" "btw2017" "euw2014" "euw2019" "kow2020" "kow2014" "ltw2013" "ltw2
> 018" {
  2.                 append using `structurind_`f''
  3.         }

.         lab var wahl    "Election ID (string)"

.                 
.         drop if stimmbezirk == 16               // DROP Munich whole city
(3 observations deleted)

.         drop if stimmbezirk == 9999     // missings
(2 observations deleted)

.         
.         * Impute German/foreigners eligible voters
.         replace wb_dt   = 100 if inlist(substr(wahl,1,3),"BTW", "LTW")
(2,964 real changes made)

.         replace wb_ausl = 0 if inlist(substr(wahl,1,3),"BTW", "LTW")
(2,964 real changes made)

.         
.         
. * MERGE with election outcomes (note: _merge=1 are redundant precints in FE-17)
.         merge 1:1 stimmbezirk wahl using "$tmp/raw_stimmbez_all_elections.dta", assert(1 3)

    Result                      Number of obs
    -----------------------------------------
    Not matched                           325
        from master                       325  (_merge==1)
        from using                          0  (_merge==2)

    Matched                             5,416  (_merge==3)
    -----------------------------------------

.         assert wahl=="BTW17" if _merge==1

.         drop if _merge==1
(325 observations deleted)

.         drop    _merge

.         
.         
. /* IMPUTE 2 missing values */ 
.         *       FE-13/SE-13 precinct 1717 missing some Strukturvariablen >
.         *               > impute district (Stadtbezirk) average vor 2 values
.         missings rep *

Checking missings in stimmbezirk ew_ges ew_dt ew_ausl_eu ew_ausl_else ew_mihi ew_ledig ew_married
    wb_18t24 wb_25t34 wb_35t44 wb_45t59 wb_60plus hh_sgl hh_kids avg_dur wahl wb_dt wb_ausl
    gebietsartschluessel stimmbezirksart wahlber_gesamt wahlber_ohne_wahlschein
    wahlber_mit_wahlschein wahlber_nicht_im_waehlerv waehler_gesamt waehler_mit_wahlschein
    ungueltige_stimmen waehler_ohne_wahlschein kow_stimmenges anz_csu anz_spd anz_fdp anz_gruene
    anz_dielinke anz_piraten anz_npd anz_oedp anz_rep anz_buendnis21_rrp anz_bp
    anz_tierschutzpartei anz_dievioletten anz_bueso anz_mlpd anz_afd anz_prodeutschland
    anz_diefrauen anz_freiewaehler anz_parteidervernunft anz_bge anz_dib anz_dkp anz_dm
    anz_diepartei anz_gesundheitsforschung anz_vpartei anz_familie anz_pbc anz_volksabstimmung
    anz_cm anz_auf anz_psg anz_pronrw anz_sgp anz_tierschutzhier anz_tierschutzallianz
    anz_buendnisc anz_big anz_diedirekte anz_diem25 anz_iiiweg anz_diegrauen anz_dierechte
    anz_liebe anz_grauepanther anz_lkr anz_menschlichewelt anz_nl anz_oekolinx anz_diehumanisten
    anz_parteifuerdietiere anz_volt anz_rosaliste anz_bia anz_fair anz_muenchenliste anz_mut
    anz_zuba anz_diefreiheit anz_hut stadtbezirk:
5416 observations with missing values

  +--------------------------------------+
  |                            # missing |
  |--------------------------------------|
  |                   ew_ges           2 |
  |                    ew_dt           2 |
  |               ew_ausl_eu           2 |
  |             ew_ausl_else           2 |
  |                  ew_mihi           2 |
  |--------------------------------------|
  |                 ew_ledig           2 |
  |               ew_married           2 |
  |                 wb_18t24           2 |
  |                 wb_25t34           2 |
  |                 wb_35t44           2 |
  |--------------------------------------|
  |                 wb_45t59           2 |
  |                wb_60plus           2 |
  |                   hh_sgl           2 |
  |                  hh_kids           2 |
  |                  avg_dur           2 |
  |--------------------------------------|
  |           kow_stimmenges        3959 |
  |              anz_piraten         755 |
  |                  anz_npd        2777 |
  |                  anz_rep        3310 |
  |       anz_buendnis21_rrp        4714 |
  |--------------------------------------|
  |     anz_tierschutzpartei        2159 |
  |         anz_dievioletten        4096 |
  |                anz_bueso        2693 |
  |                 anz_mlpd        2777 |
  |                  anz_afd         702 |
  |--------------------------------------|
  |       anz_prodeutschland        4714 |
  |            anz_diefrauen        4096 |
  |    anz_parteidervernunft        4714 |
  |                  anz_bge        4181 |
  |                  anz_dib        4799 |
  |--------------------------------------|
  |                  anz_dkp        3479 |
  |                   anz_dm        4799 |
  |            anz_diepartei        2106 |
  | anz_gesundheitsforschung        3563 |
  |              anz_vpartei        4181 |
  |--------------------------------------|
  |              anz_familie        4096 |
  |                  anz_pbc        4714 |
  |      anz_volksabstimmung        4096 |
  |                   anz_cm        4714 |
  |                  anz_auf        4714 |
  |--------------------------------------|
  |                  anz_psg        4714 |
  |               anz_pronrw        4714 |
  |                  anz_sgp        4798 |
  |       anz_tierschutzhier        4798 |
  |    anz_tierschutzallianz        4798 |
  |--------------------------------------|
  |            anz_buendnisc        4798 |
  |                  anz_big        4798 |
  |           anz_diedirekte        4798 |
  |               anz_diem25        4798 |
  |               anz_iiiweg        4798 |
  |--------------------------------------|
  |            anz_diegrauen        4798 |
  |            anz_dierechte        4798 |
  |                anz_liebe        4798 |
  |         anz_grauepanther        4798 |
  |                  anz_lkr        4180 |
  |--------------------------------------|
  |      anz_menschlichewelt        4798 |
  |                   anz_nl        4798 |
  |             anz_oekolinx        4798 |
  |        anz_diehumanisten        4180 |
  |   anz_parteifuerdietiere        4798 |
  |--------------------------------------|
  |                 anz_volt        4043 |
  |            anz_rosaliste        3959 |
  |                  anz_bia        3959 |
  |                 anz_fair        4661 |
  |        anz_muenchenliste        4661 |
  |--------------------------------------|
  |                  anz_mut        4043 |
  |                 anz_zuba        4661 |
  |          anz_diefreiheit        4012 |
  |                  anz_hut        4714 |
  +--------------------------------------+

.         cap drop tmp*

.         gen tmp_quote = ew_ges/wahlber_gesamt                   // impute total inhabitants als 
> multiple of wahlberechtigte
(2 missing values generated)

.         bys wahl stadtbezirk: egen tmp2 = mean(tmp_quote)

.         
.         replace ew_ges = floor(tmp2 * wahlber_gesamt) if missing(ew_ges)
(2 real changes made)

.         drop tmp*

.         
.         
.         *impute remaining vars (2 values)
.         foreach v of varlist wb_18t24 wb_25t34 wb_35t44 wb_45t59 /*wb_60plus*/ avg_dur ew_dt ew_
> ausl_eu /*ew_ausl_else*/ hh_sgl hh_kids ew_ledig ew_married ew_mihi {
  2.                 cap drop tmp*
  3.                 bys wahl stadtbezirk: egen tmp = mean(`v')
  4.                 replace `v' = tmp if missing(`v') & stimmbezirk == 1717
  5.         }
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)
(2 real changes made)

.                 replace wb_60plus = 100 - (wb_18t24+ wb_25t34 +wb_35t44 +wb_45t59) if missing(wb
> _60plus)
(2 real changes made)

.                 replace ew_ausl_else = 100 - (ew_dt + ew_ausl_eu) if missing(ew_ausl_else)
(2 real changes made)

.         
.                 assert ew_mihi > ew_ausl_else + ew_ausl_eu 

.                 
. *** STEP 4: Replaces values in LEVELS of indicators instead of shares ***
. 
.         // Level using #inhabitants
.                 *->Note: includes hh-level variables
.         foreach v of varlist ew_dt ew_mihi ew_ausl* ew_ledig ew_married hh_sgl hh_kids{
  2.                 assert inrange(`v',0,100) | `v' == .                            // 1717 in FE
> /SE 2013 missing ew data
  3.                 replace `v' = (`v'/100) * ew_ges
  4.         }
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)

. 
.         // Level using #eligible voters
.         foreach v of varlist wb_18t24 wb_25t34 wb_35t44 wb_45t59 wb_60plus wb_dt wb_ausl{
  2.                 assert inrange(`v',0,100)  | `v' == .                           // 1717 in FE
> /SE 2013 missing data
  3.                 replace `v' = (`v'/100) * wahlber_gesamt
  4.         }
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(5,416 real changes made)
(2,777 real changes made)

.         
.         rename stadtbezirk stadtbez

.         rename stimmbezirk sb

. 
. * save: Panel of precincts x election including election outcomes + structural indicators
.         cap drop tmp*

.         compress
  variable ew_ges was long now int
  variable wahlber_gesamt was long now int
  variable wahlber_ohne_wahlschein was long now int
  variable wahlber_mit_wahlschein was long now int
  variable waehler_gesamt was long now int
  variable waehler_mit_wahlschein was long now byte
  variable ungueltige_stimmen was int now byte
  variable waehler_ohne_wahlschein was float now int
  variable anz_csu was long now int
  variable anz_spd was long now int
  variable anz_fdp was long now int
  variable anz_gruene was long now int
  variable anz_dielinke was long now int
  variable anz_piraten was long now int
  variable anz_npd was int now byte
  variable anz_oedp was long now int
  variable anz_rep was int now byte
  variable anz_bp was long now int
  variable anz_tierschutzpartei was int now byte
  variable anz_dievioletten was int now byte
  variable anz_bueso was int now byte
  variable anz_mlpd was int now byte
  variable anz_afd was long now int
  variable anz_prodeutschland was int now byte
  variable anz_diefrauen was int now byte
  variable anz_freiewaehler was long now int
  variable anz_parteidervernunft was int now byte
  variable anz_bge was int now byte
  variable anz_dib was int now byte
  variable anz_dkp was int now byte
  variable anz_dm was int now byte
  variable anz_diepartei was long now int
  variable anz_gesundheitsforschung was int now byte
  variable anz_vpartei was int now byte
  variable anz_familie was int now byte
  variable anz_pbc was int now byte
  variable anz_volksabstimmung was int now byte
  variable anz_cm was int now byte
  variable anz_auf was int now byte
  variable anz_tierschutzhier was int now byte
  variable anz_tierschutzallianz was int now byte
  variable anz_buendnisc was int now byte
  variable anz_big was int now byte
  variable anz_diedirekte was int now byte
  variable anz_diem25 was int now byte
  variable anz_diegrauen was int now byte
  variable anz_dierechte was int now byte
  variable anz_liebe was int now byte
  variable anz_grauepanther was int now byte
  variable anz_lkr was int now byte
  variable anz_menschlichewelt was int now byte
  variable anz_nl was int now byte
  variable anz_oekolinx was int now byte
  variable anz_diehumanisten was int now byte
  variable anz_parteifuerdietiere was int now byte
  variable anz_volt was long now int
  variable anz_rosaliste was long now int
  variable anz_bia was long now int
  variable anz_fair was long now int
  variable anz_muenchenliste was long now int
  variable anz_mut was long now int
  variable anz_zuba was long now int
  variable anz_diefreiheit was long now int
  variable anz_hut was long now int
  variable stadtbez was float now byte
  (514,520 bytes saved)

.         isid  sb wahl

.         order sb wahl gebietsartschluessel stadtbez

.         save "$tmp/raw_stimmbez_full.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/raw_stimmbez_full.dta not
    found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/raw_stimmbez_full.dta
    saved

.         
. * save a second time for descriptive statistics
.         save "$newdata/raw_stimmbez_full.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/raw_stimmbez_full.dt
    > a not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/raw_stimmbez_full.dt
    > a saved

.         
. 
end of do-file
Running: 02_c_build_precinct_panel_migration.do

. /*
> 
> Input: migration_precincts.xlsx [data prepared by statistical office MUC]
> 
> Output:         $tmp/migration_precincts.dta 
> 
> Tasks:
>  * Prepare moves within and across precincts (Stimmbezirke)
>  
> Note:
>         * Precinct boundaries are already as of 2018! no conversion needed
>                 
> 
> 
> */
. 
. import excel using "$rawdata/statistical_office/migration_precincts.xlsx",  clear
(19 vars, 624 obs)

.         
.         // precinct ID
.         rename A sb_new

. 
.         rename  (B C D) (withmig1 outmig1 inmig1)       // LTW 13 (SE-13)

.                                                                                                 
> // BTW 13 = LTW13 (FE-13 = SE-13)
.         rename  (E F G) (withmig3 outmig3 inmig3)       // KOW 14 (ME14)

.                                                                                                 
> // EUW 14 = KOW14 (EuE14 = ME14)
.         rename  (H I J) (withmig5 outmig5 inmig5)       // BTW 17 (FE-17)

.         rename  (K L M) (withmig6 outmig6 inmig6)       // LTW 18 (SE-18)

.         rename  (N O P) (withmig7 outmig7 inmig7)       // EUW 19 (EuE19)

.         rename  (Q R S) (withmig8 outmig8 inmig8)       // KOW 20 (ME20)

. 
. 
.         drop if _n < 5
(4 observations deleted)

.         
.         * Remove unnecessary "0" in the middle of the precinct ID 
.         replace         sb_new = substr(sb_new,1,2) +substr(sb_new,4,.)
(619 real changes made)

.         
.         * Destring
.         destring sb_new, replace
sb_new: all characters numeric; replaced as int
(1 missing value generated)

.         drop if missing(sb_new)
(1 observation deleted)

.         
.         destring *, replace
sb_new already numeric; no replace
withmig1: all characters numeric; replaced as int
outmig1: all characters numeric; replaced as int
inmig1: all characters numeric; replaced as int
withmig3: all characters numeric; replaced as byte
outmig3: all characters numeric; replaced as int
inmig3: all characters numeric; replaced as int
withmig5: all characters numeric; replaced as int
outmig5: all characters numeric; replaced as int
inmig5: all characters numeric; replaced as int
withmig6: all characters numeric; replaced as int
outmig6: all characters numeric; replaced as int
inmig6: all characters numeric; replaced as int
withmig7: all characters numeric; replaced as int
outmig7: all characters numeric; replaced as int
inmig7: all characters numeric; replaced as int
withmig8: all characters numeric; replaced as int
outmig8: all characters numeric; replaced as int
inmig8: all characters numeric; replaced as int

.         
.         * Reshape long
.         reshape long withmig outmig inmig, i(sb_new) j(wahl_id)
(j = 1 3 5 6 7 8)

Data                               Wide   ->   Long
-----------------------------------------------------------------------------
Number of observations              619   ->   3,714       
Number of variables                  19   ->   5           
j variable (6 values)                     ->   wahl_id
xij variables:
         withmig1 withmig3 ... withmig8   ->   withmig
            outmig1 outmig3 ... outmig8   ->   outmig
               inmig1 inmig3 ... inmig8   ->   inmig
-----------------------------------------------------------------------------

.         
.         
.         * Impute FE-13 and EuE-14
.         expand 2 if wahl_id==1, gen(tmp1)
(619 observations created)

.         replace wahl_id=2 if tmp1==1
(619 real changes made)

.         
.         expand 2 if wahl_id==3, gen(tmp2)
(619 observations created)

.         replace wahl_id=4 if tmp2==1
(619 real changes made)

.         drop tmp*

.         
.         * Lab vars
.         lab var sb_new  "Harmonized precinct ID (as of 2018)"

.         lab var withmig "Abs. migr. within precinct since last elec"

.         lab var outmig  "Abs. migr. out of precinct since last elec"

.         lab var inmig   "Abs. migr. into precinct since last elec"

. 
.         lab def wahl_id 0 "BTW2009" 1 "LTW2013" 2 "BTW2013" 3 "KOW2014" 4 "EUW2014" 5 "BTW2013" 
> 6 "LTW2018" 7 "EUW2019" 8 "KOW2020"

.         lab val wahl_id wahl_id

.         lab var wahl_id "Election ID"   

.         
.         
.         * Save: Panel of precincts (boundaries as of 2018) x election
.         isid sb_new wahl_id

.         save "$tmp/migration_precincts.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/migration_precincts.dta
    not found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/migration_precincts.dta
    saved

. 
end of do-file
Running: 03_prep_shapefiles.do

. /*
> 
> Input: Shapefiles from $rawdata/shp
> 
> Output: 
>         > $tmp/ltw18_sb_area.dta [area of precincts]
>         > $newdata/ltw18_sb_mapping.dta
>         > $tmp/stadtbezirke_mapping.dta
> 
> Main tasks:
>         > Prepare shapefiles for mapping: precincts (Stimmbezirke) of 2018 and districts (Stadtb
> ezirke)
>         > Compute area of precincts as of 2018 
>  
> */
.         // To display maps correctly, Stata command "spmap" (or "grmap") requires that shp files
>  be
.         // transformed to dta files AND that any geopgraphical information (lat/lon) is projecte
> d into the same reference system.
.         // "shp2dta"  or  "spshape2dta" does the first and "geo2xy" does the latter.
. 
. 
. cd "$rawdata/shp"
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication\02_rawdata\shp

. clear   

. 
.  *** I Precincts ***
.  
.         ** CREATE shape layer file (_shp.dta) and an attributes layer (data file)
.         // > gens : "landtagwahl2018_stimmbezirke_shp.dta" and "landtagwahl2018_stimmbezirke.dta
> "
.                 spshape2dta  landtagwahl2018_stimmbezirke.shp, replace 
  (importing .shp file)
  (importing .dbf file)
  (creating _ID spatial-unit id)
  (creating _CX coordinate)
  (creating _CY coordinate)

  file landtagwahl2018_stimmbezirke_shp.dta created
  file landtagwahl2018_stimmbezirke.dta     created

.                 spshape2dta  landtagwahl2018_stimmbezirke_newprj.shp, replace
  (importing .shp file)
  (importing .dbf file)
  (creating _ID spatial-unit id)
  (creating _CX coordinate)
  (creating _CY coordinate)

  file landtagwahl2018_stimmbezirke_newprj_shp.dta created
  file landtagwahl2018_stimmbezirke_newprj.dta     created

.                 
.         ** PULL coordinates file: Transform geo coordinates in degrees into "Web Mercator" proje
> ction in meters (here: shp already in Mercator projection)
.                 use  "landtagwahl2018_stimmbezirke_shp.dta", clear

.                                 
.          * Compute precinct area (closed polygons)
.                 // Generate variables for next point's coordinates
.                 bys _ID (shape_order): gen double next_x = _X[_n+1] 
(621 missing values generated)

.                 bys _ID (shape_order): gen double next_y = _Y[_n+1] 
(621 missing values generated)

. 
.                 // Compute individual terms for each pair of points
.                 gen double term = (_X * next_y) - (next_x * _Y)
(1,242 missing values generated)

. 
.                 // Compute the area for each polygon
.                 bys _ID: egen double polygon_area = total(term)

. 
.                 // Finalize the area computation by taking the absolute value and dividing by 2
.                 replace polygon_area = abs(polygon_area)/2
(33,973 real changes made)

.                 
.                 // Gen area in SQKM 
.                 gen     area_sb_ltw18 = polygon_area/1000000 

.                 
.                 // KEEP unique precincts and save area data 
.                 collapse (mean) area_sb_ltw18, by(_ID)

.                 lab var area_sb_ltw18 "Precinct area in sqkm, 2018"

.                 
.                 // MERGE precinct ids 
.                 merge 1:m _ID using "landtagwahl2018_stimmbezirke.dta", keepusing(LTW_SB_2_1) as
> sert(3)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                               620  (_merge==3)
    -----------------------------------------

.                 destring LTW_SB_2_1, gen(sb_new)
LTW_SB_2_1: all characters numeric; sb_new generated as int

.                 duplicates drop sb_new, force

Duplicates in terms of sb_new

(2 observations deleted)

.                 lab var sb_new "Precinct ID, LTW 18"

.                 
.                 // SAVE: surface area, precincts 2018
.                 keep sb_new area_sb_ltw18

.                 isid sb_new 

.                 compress
  (0 bytes saved)

.                 save "$tmp/ltw18_sb_area.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/ltw18_sb_area.dta not
    found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/ltw18_sb_area.dta saved

.                 
.                 
.         ** PULL attribute file
.                 use "landtagwahl2018_stimmbezirke.dta", clear

.                 
.                 destring LTW_SB_2_1, gen(sb_new)
LTW_SB_2_1: all characters numeric; sb_new generated as int

.                 
.                 // save precinct data for MAPs
.                 save "$newdata/ltw18_sb_mapping.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/ltw18_sb_mapping.dta
    not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/ltw18_sb_mapping.dta
    saved

.                 
.                 
.  *** II. DISTRICTS ***
.                 * CREATE shape layer file (_shp.dta) and an attributes layer data file
.                 spshape2dta  stadtbezirke.shp, replace          
  (importing .shp file)
  (importing .dbf file)
  (creating _ID spatial-unit id)
  (creating _CX coordinate)
  (creating _CY coordinate)

  file stadtbezirke_shp.dta created
  file stadtbezirke.dta     created

.                 
.         * PULL coordinates file: Transform geo coordinates in degrees into "Web Mercator" projec
> tion in meters
.                 use "stadtbezirke_shp.dta", clear

. 
.                         // note: correction needed here to properly overlay precincts
.                         replace _X = _X +145 if !missing(_X)
(14,538 real changes made)

.                         replace _Y = _Y +144 if !missing(_Y)
(14,538 real changes made)

. 
.                 save "stadtbezirke_shp.dta", replace
file stadtbezirke_shp.dta saved

.                 
.         * PULL attribute file
.                 use "stadtbezirke.dta", clear

.                 
.                 destring SB_NUMMER, replace
SB_NUMMER: all characters numeric; replaced as byte

.                 gen stadtbez= SB_NUMMER

.         
.                 merge 1:n _ID using  "stadtbezirke_shp.dta", assert(3) nogen

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                            14,565  
    -----------------------------------------

.                 
.          *sort: IMPORTANT to SORT otherwise there are random lines drawn!
.                 sort  _ID shape_order

.         
.         * save Stimmbezirke data for MAPs
.         drop X Y

.         save "$tmp/stadtbezirke_mapping.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbezirke_mapping.dta
    not found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stadtbezirke_mapping.dta
    saved

.                 
.                 
. cd "$project"           
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication

. 
. 
end of do-file
Running: 04_prep_conv_keys_ltw18.do

. /*
> 
> Input file: Umrechnung_Wahlen_2013-2020_auf_LTW2018.xlsx [raw correspondences from statistical o
> ffice MUC]
>                         
> Output file: tmp/convkeys_ltw2018.dta [Conversion keys]
> 
> Main tasks: prep conversion keys for harmonizing precinct boundaries of all 
>                                 election since 2013 to the boundaries of SE-18
>         
> 
> Notes:  
>         > Basis for conversions are all eligible voters in election X, i.e. 
>                         Germans 18+ in FE/SE, Germans and EU-Foreigners in EuE and ME.
>         > This is only relevant for precinct-level variables such as election outcomes;
>         (distances and reassignments are computed at the address level.)
>         
> */
. 
. 
. ********************************************************************************
. // Prep conversion file: Election x to SE-18  //
. *******************************************************************************
.         
. * READ individual sheets & append
. 
.         foreach x in "LTW2013" "BTW2013" "KOW2014" "EUW2014" "BTW2017" "KOW2020" "EUW2019"  {
  2. 
.                 import excel using ///
>                 "$rawdata/statistical_office/Umrechnung_Wahlen_2013-2020_auf_LTW2018.xlsx", ///
>                                 sheet("`x'") cellrange("A4") clear
  3.                 
.                 * clean sheet
.                 assert C[1] == "Deutsche"
  4.                 drop if _n == 1
  5.                 drop if A == "Gesamtsumme"
  6.                 replace C = subinstr(C, "-","",.)
  7.                 replace D = subinstr(D, "-","", .)
  8.                 keep A B C D
  9.                 destring A B C D, replace
 10.                 
.                 rename A        sb_ltw2018
 11.                 rename B        sb
 12.                 lab var         sb_ltw2018 "Precinct LTW 2018"
 13.                 lab var         sb                 "Precinct (election-specific)"
 14.                 
.                 * For the very few missings: ASSUME missing = 0
.                 replace C = 0 if missing(C)
 15.                 replace D = 0 if missing(D)
 16.                 
.                 * Compute Basis of eligible voters [EUW & KOW w/ foreigners, else w/o]
.                 if inlist("`x'","KOW2014","KOW2020", "EUW2014", "EUW2019"){
 17.                         gen wahlb = C + D       // eligible voters in election x = Germans + 
> EU-Foreigners
 18.                 }
 19.                 else {
 20.                         gen wahlb = C           // eligible voters in election x = only Germa
> ns
 21.                 }
 22.                 
.                 drop C D
 23.                 
.                 * Compute shares
.                 
.                 // gen: total eligible voters by precinct in election x
.                 bys sb: egen tot_wb = total(wahlb)
 24.                 
.                 // gen: conv_wgt = conversion weight
.                 gen conv_wgt = wahlb/ tot_wb
 25.                 lab var conv_wgt "Conversion key from election x to SE-18"
 26.                 
.                 drop wahlb tot_wb
 27.                 
.                 // gen Election ID
.                 gen     wahl = ustrregexra("`x'", "(?=\w*)20(?=\d{2})","")              // remov
> es "20" from e.g., EUW2014 => EUW14
 28.                 lab var wahl "Election"
 29.                 
.                 // save
.                 tempfile conv_`x'_ltw2018
 30.                 save  `conv_`x'_ltw2018'
 31.         }
(6 vars, 1,567 obs)
(1 observation deleted)
(0 observations deleted)
(1 real change made)
(19 real changes made)
A: all characters numeric; replaced as long
B: all characters numeric; replaced as long
C: all characters numeric; replaced as int
(1 missing value generated)
D: all characters numeric; replaced as int
(19 missing values generated)
(1 real change made)
(19 real changes made)
(1 missing value generated)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000001.tmp saved as .dta format
(6 vars, 1,567 obs)
(1 observation deleted)
(0 observations deleted)
(1 real change made)
(19 real changes made)
A: all characters numeric; replaced as long
B: all characters numeric; replaced as long
C: all characters numeric; replaced as int
(1 missing value generated)
D: all characters numeric; replaced as int
(19 missing values generated)
(1 real change made)
(19 real changes made)
(1 missing value generated)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000002.tmp saved as .dta format
(6 vars, 1,568 obs)
(1 observation deleted)
(0 observations deleted)
(1 real change made)
(20 real changes made)
A: all characters numeric; replaced as long
B: all characters numeric; replaced as long
C: all characters numeric; replaced as int
(1 missing value generated)
D: all characters numeric; replaced as int
(20 missing values generated)
(1 real change made)
(20 real changes made)
(1 missing value generated)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000003.tmp saved as .dta format
(6 vars, 1,569 obs)
(1 observation deleted)
(0 observations deleted)
(2 real changes made)
(20 real changes made)
A: all characters numeric; replaced as long
B: all characters numeric; replaced as long
C: all characters numeric; replaced as int
(2 missing values generated)
D: all characters numeric; replaced as int
(20 missing values generated)
(2 real changes made)
(20 real changes made)
(1 missing value generated)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000004.tmp saved as .dta format
(6 vars, 689 obs)
(1 observation deleted)
(0 observations deleted)
(1 real change made)
(1 real change made)
A: all characters numeric; replaced as int
B: all characters numeric; replaced as int
C: all characters numeric; replaced as int
(1 missing value generated)
D: all characters numeric; replaced as int
(1 missing value generated)
(1 real change made)
(1 real change made)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000005.tmp saved as .dta format
(6 vars, 1,570 obs)
(1 observation deleted)
(0 observations deleted)
(2 real changes made)
(3 real changes made)
A: all characters numeric; replaced as int
B: all characters numeric; replaced as int
C: all characters numeric; replaced as int
(2 missing values generated)
D: all characters numeric; replaced as int
(3 missing values generated)
(2 real changes made)
(3 real changes made)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000006.tmp saved as .dta format
(6 vars, 648 obs)
(1 observation deleted)
(0 observations deleted)
(0 real changes made)
(0 real changes made)
A: all characters numeric; replaced as int
B: all characters numeric; replaced as int
C: all characters numeric; replaced as int
D: all characters numeric; replaced as int
(0 real changes made)
(0 real changes made)
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000007.tmp saved as .dta format

. clear

. 
. * Append
.         foreach x in "LTW2013" "BTW2013" "KOW2014" "EUW2014" "BTW2017" "KOW2020" "EUW2019" {
  2.                 append using  `conv_`x'_ltw2018'
  3.         }

.         
.         
. * Strip "0" from precinct ID
.         tostring sb_ltw2018 sb, replace
sb_ltw2018 was long now str5
sb was long now str5

.         foreach v of varlist sb_ltw2018 sb {
  2.                 replace `v' = ///
>                                 substr(`v',1,1) + substr(`v',3,.) if strlen(`v') == 4
  3.                 replace `v' = ///
>                                 substr(`v',1,2) + substr(`v',4,.) if strlen(`v') == 5
  4.         }
(2,872 real changes made)
(6,299 real changes made)
(2,872 real changes made)
(6,299 real changes made)

.         destring sb_ltw2018 sb, replace
sb_ltw2018: all characters numeric; replaced as int
sb: all characters numeric; replaced as int

.         
. * Save
.         save "$tmp/convkeys_ltw2018.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/convkeys_ltw2018.dta not
    found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/convkeys_ltw2018.dta saved

.         
. 
end of do-file
Running: 05_address_panel_convert_to_ltw18.do

. /*
> 
> Input:  
>         > $tmp/raw_stimmbez_all_elections.dta [precinct-level data with year-specific precinct]
>         > $tmp/panel_wahlen.dta [Address-level election data with year-specific boundaries]
>         > $tmp/convkeys_ltw2018.dta [Conversion keys]
>                                 
> Output:         $tmp/panel_wahlen_covted_ltw18.dta [Address-level election data with boundaries 
> as of SE-18]
> 
>                                 
> Main tasks:
>         A) Convert Election-specific variables to precinct boundaries as of SE-18 and
>         B) assign to each address its precinct as of SE-18.
> 
> 
> Note:   * Macro "sb_vars" defined below, contains precinct-level variables to be
>                         converted => adjust if necessary
> 
>                 * sb_new := precinct as of SE-18
>                 * sb_old := Original precinct
>                 
> */
. 
. 
. *** Define precinct-Variables to be converted
. // NB: These variables will be SUMMED
. global sb_vars  wahlber_gesamt wahlber_ohne_wahlschein wahlber_mit_wahlschein ///
>                                 wahlber_nicht_im_waehlerv waehler_gesamt waehler_mit_wahlschein 
> ///
>                                 ungueltige_stimmen ew_* wb_* hh_sgl hh_kids avg_dur anz_* kow_st
> immenges        

. 
. /// A) Convert precinct-level Data for all elections ///
> 
. * 1) Pull precinct-level data for all elections
.         use "$tmp/raw_stimmbez_full.dta", clear

.         
. 
. * 2) Merge w/ conversion keys
. *        NB: Only Levels can be converted, no shares!
.         merge 1:n wahl sb using "$tmp/convkeys_ltw2018.dta", keep(1 3)

    Result                      Number of obs
    -----------------------------------------
    Not matched                           618
        from master                       618  (_merge==1)
        from using                          0  (_merge==2)

    Matched                             9,167  (_merge==3)
    -----------------------------------------

.                 
.                 assert wahl == "LTW18"  if _merge == 1

.                 assert _merge ==1                       if wahl == "LTW18"

.                 assert !missing(conv_wgt)       if wahl != "LTW18"

.                 drop _merge

.         
.         * gen pseudo key for LTW 2018
.         replace conv_wgt = 1    if wahl == "LTW18"
(618 real changes made)

.         replace sb_ltw2018 = sb if wahl == "LTW18"
(618 real changes made)

.         
. 
.         
. * 3) Convert variables
.         foreach v of varlist $sb_vars {
  2.                 gen covted_`v' = `v' * conv_wgt
  3.                 local lb : variable label `v'
  4.                 lab var covted_`v' "`lb'"
  5.                 drop `v'
  6.         }
(1,569 missing values generated)
(5,318 missing values generated)
(5,088 missing values generated)
(8,220 missing values generated)
(4,700 missing values generated)
(7,573 missing values generated)
(4,400 missing values generated)
(5,318 missing values generated)
(1,565 missing values generated)
(8,220 missing values generated)
(7,573 missing values generated)
(8,220 missing values generated)
(8,450 missing values generated)
(9,097 missing values generated)
(6,883 missing values generated)
(9,097 missing values generated)
(4,696 missing values generated)
(7,832 missing values generated)
(8,479 missing values generated)
(7,571 missing values generated)
(8,218 missing values generated)
(7,571 missing values generated)
(8,218 missing values generated)
(8,218 missing values generated)
(8,218 missing values generated)
(8,218 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(8,520 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(9,138 missing values generated)
(8,520 missing values generated)
(9,138 missing values generated)
(7,569 missing values generated)
(6,650 missing values generated)
(6,650 missing values generated)
(8,216 missing values generated)
(8,216 missing values generated)
(7,598 missing values generated)
(8,216 missing values generated)
(6,654 missing values generated)
(8,219 missing values generated)
(6,650 missing values generated)

.         
. 
. * 4) Collapse (SUM) to new precinct
. 
.         // copy labels
.         foreach v of varlist * {
  2.                 local x = subinstr("`v'","covted_","",.)
  3.                 local `x'_lb : variable label `v'
  4.         }

.         
.         collapse (sum) covted_*, by(wahl sb_ltw2018) fast

. 
.         rename covted_* *

.         
.         // re-label                                             
.         foreach v of varlist * {
  2.                 lab var `v' "``v'_lb'"
  3.         }

. 
. 
. * 5) Save precinct x election panel w/ boundaries as of 2018
. 
.         * rename: sb_new = sb as of SE-18
.         rename  sb_ltw2018 sb_new

.         
.         * gen year variable
.         gen     jahr =  "20"+substr(wahl,-2,.)

.         destring jahr, replace
jahr: all characters numeric; replaced as int

.         lab var jahr "Election year"

.         
.         * save converted precinct-data
.         save "$tmp/stimmbez_all_elections_covted_ltw18.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stimmbez_all_elections_covt
    > ed_ltw18.dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/stimmbez_all_elections_covt
    > ed_ltw18.dta saved

.         
.         
. /// B) Convert Address-level data (8 elections) and merge with precinct-data ///
> 
. * 1) Pull original address-level election data
.         use "$tmp/panel_wahlen.dta", clear

.                 
. * 1.1) Assign to each address precinct as of SE-18
.         
.         // Note: district (stadtbez) doesn't change over time
.         bys voter_id (stadtbez): assert stadtbez[1] == stadtbez[_N]

.         
.         // gen sb_new := precinct as of SE-18
.         gen tmp = sb if wahl == "LTW18"
(1,206,232 missing values generated)

.         bys voter_id (tmp): gen sb_new = tmp[1]

.         lab var sb_new          "Precinct as of SE-18"

.         assert !missing(sb_new)

.         assert sb_new==sb if wahl_id==6

.         drop tmp*

.         
.         * mark old precinct
.         rename  sb sb_old

.         lab var sb_old "Original precinct of voter_id"

.                 
. * 2) Merge converted precinct oucomes to addresses (master-only = FE-09)                        
.         merge n:1 wahl sb_new using "$tmp/stimmbez_all_elections_covted_ltw18.dta", assert(1 3)

    Result                      Number of obs
    -----------------------------------------
    Not matched                       150,779
        from master                   150,779  (_merge==1)
        from using                          0  (_merge==2)

    Matched                         1,206,232  (_merge==3)
    -----------------------------------------

.         assert wahl == "BTW09" if _merge == 1

.         drop _merge

.         
.         
.         order voter_id jahr wahl sb_new sb_old

. 
. * 3) Convert Strukturindikatoren back to shares
.                 // Share anhand von EINWOHNER (residents)
.                 *->Note: household level variables included
.         foreach v of varlist ew_dt ew_ausl* ew_mihi ew_ledig ew_married hh_sgl hh_kids{
  2.                 replace `v' = `v' /ew_ges
  3.                 assert inrange(`v',0,1) if wahl_id!= 0 // "FE-09"
  4.         }
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)

. 
.         // Share given eligible voters
.         foreach v of varlist wb_18t24 wb_25t34 wb_35t44 wb_45t59 wb_60plus wb_dt wb_ausl{
  2.                 replace `v' = `v' / wahlber_gesamt
  3.                 assert inrange(`v',0,1) if wahl_id != 0 // "FE-09"
  4.         
.         }
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(1,206,232 real changes made)
(603,116 real changes made)

.         
. * 4) Generate shares of party outcomes
.         foreach v of varlist anz_* {
  2.                 local partei = subinstr("`v'","anz_","",.)      
  3.                 gen     shr_`partei' = `v'/(waehler_gesamt-ungueltige_stimmen) if !inlist(wah
> l, "KOW20", "KOW14")
  4.                 replace shr_`partei' = `v'/kow_stimmenges if inlist(wahl, "KOW20", "KOW14")
  5.                 replace shr_`partei' = 0 if missing(shr_`partei')
  6.                 lab var shr_`partei' "Party share of `partei' (in-person)"
  7.         }
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)
(452,337 missing values generated)
(301,558 real changes made)
(150,779 real changes made)

. 
.         
. * 5) Finalize and save
.         
.  * GEN wahl_type
.         gen tmp = substr(wahl,1,3)

.         encode tmp, gen(wahl_type)

.         lab var wahl_type "Election type ID"

. 
.         // save
.         order   voter_id wahl wahl_type jahr sb_new sb_old

.         compress
  variable wahl_type was long now byte
  variable sb_new was float now int
  (6,785,055 bytes saved)

.         cap drop tmp*

.         isid voter_id wahl_id

.         save "$tmp/panel_wahlen_covted_ltw18.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/panel_wahlen_covted_ltw18.d
    > ta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/panel_wahlen_covted_ltw18.d
    > ta saved

. 
end of do-file
Running: 06_a_build_polling_place_panel.do

. /*
> 
> Input: tmp/wl_sb_assignments_clean.dta [Assignment of precinct to PP in each election]
> 
> Output: newdata/wahllokal_change.dta [panel of PP, with activity status and category]
> 
> Main tasks:
> A) Build balanced panel of polling places (PP) (German: Wahllokale (wl)) with dummy if PP is act
> ive in election t (wl_active)
> B) Gen variables of interest at the PP level, esp. for changes in PP activity status 
>         over time & type of PP (school, restaurant, retirement  home, etc.)
>         
> Note: Vars at PP-level characteristics have prefix wl_  
> 
> 
> */
. 
. 
.  ** PULL: Assignment of precint to PP in each election  
.  use "$tmp/wl_sb_assignments_clean.dta", clear 

.         isid sb wahl_id

.         
.         // KEEP unique PP in each election 
.         duplicates drop wl_id wahl_id, force 

Duplicates in terms of wl_id wahl_id

(4,237 observations deleted)

.         drop sb wahl

.         
.         // FILL to create BALANCED panel (total of 9 elections, incl. FE-09)
.         fillin wl_id wahl_id

.         sort wl_id wahl_id

.         
.         // fill in other vars  (missings created)
.         foreach v of varlist wl_typ lon_wl lat_wl {
  2.                 bys wl_id (_fillin): replace `v'=`v'[1] if missing(`v')
  3.         }
(848 real changes made)
(848 real changes made)
(848 real changes made)

.         
.         // gen wl_active: dummy that tracks PP's activity status over 9 elections
.         recode _fillin (0=1) (1=0), gen(wl_active)
(2691 differences between _fillin and wl_active)

.         lab var wl_active "Dummy (PP active in election t)"

.         drop _fillin

.         
.         
.         // wl_dropped: dummy = 1 if WL was active in t-1 and inactive in t
.         bys wl_id (wahl_id): gen tmp1 = wl_active==wl_active[_n-1]

.         gen wl_dropped = (tmp1==0 & wl_active==0)

.         replace wl_dropped=0 if wahl_id==0
(98 real changes made)

.         lab var wl_dropped "Dummy (PP was active in t-1 and inactive now)"

.         
.         // wl_dropped_lag: dummy = 1 if WL is active in t and will be inactive in t+1
.         bys wl_id (wahl_id): gen wl_dropped_lag = wl_dropped[_n+1]
(299 missing values generated)

.         replace wl_dropped_lag=0 if wl_dropped_lag==.
(299 real changes made)

.         lab var wl_dropped_lag "Dummy (PP active now but inactive in t+1)"

.         
.         // wl_added: dummy = 1 if WL inactive in t-1 and active in t
.         gen wl_added = (tmp1==0 & wl_active==1)

.         replace wl_added=0 if wahl_id==0
(201 real changes made)

.         label var wl_added "Dummy (PP inactive now but active in t-1)"

.         drop tmp*       

.         
.         
.   // gen wl_kat := PP categories (eg. school) based on PP description (wl_typ)
.         gen     wl_kat = "x"

.         lab var wl_kat "Polling place building type"

.         
.         gen wl_typ_clean = wl_typ

. 
.         replace wl_typ_clean = lower(wl_typ_clean)
(2,691 real changes made)

. 
.         gen tmp =       strpos(wl_typ_clean, "schul")>0 | strpos(wl_typ_clean, "gymnasium") >0 |
>  ///
>                                 strpos(wl_typ_clean, "bildungs") >0 | strpos(wl_typ_clean, "inst
> itut") >0 | ///
>                                 strpos(wl_typ_clean, "sonderpäd") >0 | strpos(wl_typ_clean, "fos
> ")>0  

. 
.         replace wl_kat = "Schools and other educational entities" if tmp > 0
variable wl_kat was str1 now str38
(1,890 real changes made)

.         drop tmp*

. 
.         gen tmp =       strpos(wl_typ_clean, "kirche")>0 | strpos(wl_typ_clean, "pfarr")>0 | ///
>                                 strpos(wl_typ_clean, "stift")>0 | strpos(wl_typ_clean, "pfarr")>
> 0

.         replace wl_kat = "Church-affiliated facilities" if tmp > 0
(306 real changes made)

.         drop tmp*

. 
.         gen tmp =       strpos(wl_typ_clean, "alten")>0 | strpos(wl_typ_clean, "demenz")>0 | ///
>                                 strpos(wl_typ_clean, "senioren")>0 | strpos(wl_typ_clean, "kursa
> na")>0 | ///
>                                 strpos(wl_typ_clean, "kolping")>0 | strpos(wl_typ_clean, "gehörl
> osen")>0 | ///
>                                 strpos(wl_typ_clean, "pflege")>0

.         replace wl_kat = "Retirement and nursing homes" if tmp > 0
(162 real changes made)

.         drop tmp*

. 
.         gen tmp =       strpos(wl_typ_clean, "hotel")>0 | strpos(wl_typ_clean, "gasthaus")>0 | /
> //
>                                 strpos(wl_typ_clean, "gaststätte")>0 | strpos(wl_typ_clean, "res
> taurant")>0

.         replace wl_kat = "Hotels and restaurants" if tmp > 0
(72 real changes made)

.         drop tmp*

. 
.         gen tmp =       strpos(wl_typ_clean, "jugend")>0 | strpos(wl_typ_clean, "sport")>0 | ///
>                                 strpos(wl_typ_clean, "turner")>0 | strpos(wl_typ_clean, "freizei
> t")>0 | ///
>                                 strpos(wl_typ_clean, "esv")>0 | strpos(wl_typ_clean, "mosaik")>0
>  | ///
>                                 strpos(wl_typ_clean, "psv")>0 

.         replace wl_kat = "Youth and sports centers" if tmp > 0
(99 real changes made)

.         drop tmp*

. 
.         gen tmp =       strpos(wl_typ_clean, "bibliothek")>0 

.         replace wl_kat = "Libraries" if tmp > 0
(18 real changes made)

.         drop tmp*

.         
.         replace wl_kat = "Other" if wl_kat == "x"
(171 real changes made)

. 
.         //manual correction
.         replace wl_kat = "Other" if wl_typ_clean=="bayer. staatsministerium für gesundheit und p
> flege"
(9 real changes made)

.         replace wl_kat = "Schools and other educational entities" if wl_typ_clean=="städt. beruf
> sschule f.d. hotel-, gaststätten- u. braugewerbe, eingang sieboldstr."
(9 real changes made)

.         replace wl_kat = "Schools and other educational entities" if wl_typ_clean=="schulzentrum
>  pfarrer-grimm-str. (neubau)"
(9 real changes made)

. 
.         drop wl_typ_clean

.         
.         * dummy for schools
.         gen     wl_school = wl_kat=="Schools and other educational entities"

.         lab var wl_school "Dummy (PP is a school)"

. 
. 
. 
. * save: Balanced Panel of Polling locations tracking activity status
.         isid wl_id wahl_id

.         compress
  variable wl_dropped was float now byte
  variable wl_dropped_lag was float now byte
  variable wl_added was float now byte
  variable wl_school was float now byte
  (32,292 bytes saved)

.         save "$newdata/wahllokal_change.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/wahllokal_change.dta
    not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/wahllokal_change.dta
    saved

. 
. 
. 
end of do-file
Running: 06_b_calc_distances_bw_pp.do

. /*
> 
> Input: tmp/panel_wahlen_covted_ltw18.dta [address panel converted to 2018 delineations]
> 
> Output: tmp/voter_panel_pp_dist.dta
>                         [address panel with distances between polling locations (wl_street_dist)
> ]
> 
> Main task: Calculate distances BETWEEN old and new polling locations
> 
> 
> Note: 
>         > To calculate walking distances, module 'osrmtime' is required; to install follow
>                 the following steps (only for windows): 
> 
>                 1. osrmtime package downloaded from github (https://github.com/christophrust/osr
> mtime),
>                         saved & unzipped in folder: 05_package
>                 2. Downloaded OSRM basemap for 'Oberbayern' from http://download.geofabrik.de/eu
> rope/germany/bayern.html
>                         and saved in folder: 05_package/osrm_basemaps
>                 3. to install, execute:
>                         cd "$project/05_packages/osrmtime_release1.3.3/"
>                         net describe osrmtime.pkg, from("$project/05_packages/osrmtime_release1.
> 3.3/")
>                         net install osrmtime.pkg
>                         net get osrmtime.pkg
>                         shell osrminstall.cmd
>                         cd "$project"
>                 5. prepare basemaps, execute:
>                         osrmprepare, mapfile("$project/05_packages/osrm_basemaps/oberbayern-late
> st.osm.pbf") profile(foot) ///
>                         osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14") 
> 
> 
> */
. 
. 
. ** PULL: voter-address panel
. use "$tmp/panel_wahlen_covted_ltw18.dta", clear

. 
.         // keep relevant vars
.         keep voter_id wahl_id wl_id lat_wl lon_wl

. 
.         // gen lags for Polling place
.         gen double l_lat_wl = .
(1,357,011 missing values generated)

.         gen double l_lon_wl = .
(1,357,011 missing values generated)

.         gen l_wl_id = ""
(1,357,011 missing values generated)

. 
.         sort voter_id wahl_id

.         bys voter_id (wahl_id): replace l_wl_id = wl_id[_n-1]
(1,206,232 real changes made)

.         bys voter_id (wahl_id): replace l_lon_wl = lon_wl[_n-1]
(1206232 real changes made)

.         bys voter_id (wahl_id): replace l_lat_wl = lat_wl[_n-1]
(1206232 real changes made)

.         
.         // drop FE-09
.         drop if wahl_id==0 
(150,779 observations deleted)

. 
.         // ID for unique pair of current and past PP (to calc distances)
.         egen pair_id = group(l_wl_id wl_id)

.         
.         // TEMPSAVE
.         tempfile panel_wl_lag

.         save `panel_wl_lag'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000001.tmp saved as .dta format

. 
.         // KEEP only unique pairs
.         drop voter_id wahl_id

.         gduplicates drop pair_id, force

Duplicates in terms of pair_id

(1,205,232 observations deleted)

. 
. 
.  * Calculate walking distance between PP in t and t-1
.         cd "$project/05_packages/osrmtime_release1.3.3/"
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication\05_packages\osrmtime_release1.3.3

.          osrmtime lat_wl lon_wl l_lat_wl l_lon_wl, mapfile("$project/05_packages/osrm_basemap/ob
> erbayern-latest.osrm") ///
>                 osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14")
------------------------------------------------------------
Traveltime and Distance with OSRM

Check for running OSRM: not running!
Starting OSRM           now running!
Calculating:
0%---10%---20%---30%--40%---50%---60%--70%---80%---90%--100%

finished calculation!
------------------------------------------------------------

.         cd "$project"   
\\vmpfs-int\ag-int$\05_Forschungsprojekte\voting\Replication

.         
.         rename  distance wl_street_dist

.         assert wl_street_dist==0 if wl_id==l_wl_id

.         replace wl_street_dist=wl_street_dist/1000 // rescale km
(748 real changes made)

.         lab var wl_street_dist "street distance b/w polling place in t and t-1 in km"

.         
. 
.         // merge back to full panel
.         keep pair_id wl_street_dist

.         merge 1:m pair_id using `panel_wl_lag', assert(3) nogen
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                         1,206,232  
    -----------------------------------------

.                 
.         // drop lags 
.         drop l_*

. 
.  * save: 
.         compress
  variable pair_id was float now int
  (2,412,464 bytes saved)

.         isid voter_id wahl_id 

.         save "$tmp/voter_panel_pp_dist.dta", replace
(file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/voter_panel_pp_dist.dta
    not found)
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/tmp/voter_panel_pp_dist.dta
    saved

. 
end of do-file
Running: 07_finalize_address_panel_ltw18.do

. /*
> 
> Main input:
>         > tmp/panel_wahlen_covted_ltw18.dta [elections w/ addresses, harmonized boundaries to LT
> W 2018]
>         > newdata/wahllokal_change.dta          [changes in polling places (PP,(used to define t
> reatment]
>         > tmp/voter_panel_pp_dist.dta           [distances b/w old and new PP]
>         
> Output: newdata/estimation_prep_ltw18_voter.dta [final dataset at address level]
> 
> Main tasks:     
>         > Merge relevant datasets
>         > Gen different treatment variables (change in polling location, distance change)
>         > Drop 2009 data (only used to define changes for 2013)
>                                 
> */
. 
. 
. //// Voter-ADDRESS LEVEL ////           
> 
. *** Pull data: address-level data, converted to 2018 boundaries
.         use "$tmp/panel_wahlen_covted_ltw18.dta", clear

.         
. * Drop redundant variables
.                 drop lat* lon*

.                 
. ** MERGES                       
.         * MERGE PP-specific info
.                 merge m:1 wl_id wahl_id using "$newdata/wahllokal_change" , assert(2 3) keep(3) 
> nogen   
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                         1,357,011  
    -----------------------------------------

.                 assert wl_active == 1

.                 drop wl_active  

.                 
.         
.         * MERGE distances b/w old and new PP
.         merge 1:1 voter_id wahl_id using "$tmp/voter_panel_pp_dist", assert(1 3) keepusing(wl_st
> reet_dist)
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                       150,779
        from master                   150,779  (_merge==1)
        from using                          0  (_merge==2)

    Matched                         1,206,232  (_merge==3)
    -----------------------------------------

.         assert wahl_id==0 if _merge==1

.         drop _merge 

.         
. 
. ** Gen Variables        
.         * gen: changed_wl = 1 (for voter_id) if PP changed relative to last election
.                 gen     changed_wl = 0

.                 bys voter_id (wahl_id): replace changed_wl = 1 if wl_id[_n] != wl_id[_n-1] & wah
> l_id > 0
(147874 real changes made)

.                 lab var changed_wl "=1 if PP changed from last election"

.                 
.                 
.         * GEN TREATMENT variables
.          * treat_simple := indicator if PP changed
.                 gen     treat_simple = changed_wl

.                 lab var treat_simple "Treated: PP changed for any reason (= changed_wl)"

.                 
.          * del_street_dist:= absolute change in distance
.                 bys voter_id (wahl_id): gen del_street_dist = street_dist[_n] - street_dist[_n-1
> ]
(150,779 missing values generated)

.                 replace del_street_dist = 0 if changed_wl == 0
(150,779 real changes made)

.                 lab var del_street_dist "Change in street_dist (due to PP change)"

.                 
.         
.         * GEN: street_increased/ street_decreased := dummy whether distance change is positive (
> negative)
.                 gen                     street_increased = (del_street_dist>0 & treat_simple==1)
>  // distance increased

.                 label var       street_increased "Dummy if street distance increased"

.                 gen             street_decreased = (del_street_dist<0 & treat_simple==1)        
>         // distance decreased

.                 label var       street_decreased "Dummy if street distance decreased"           
>         

.         
.          * Reason for change in polling location
.          
.                 * Assume REASON= "recruitment" if new PP inactive before OR old PP inactive now
.                 * and    REASON= "precinct reconfiguration/consolidation" else
.                         // treat_consol : = 1 if new PP active before AND old PP still active
.                         bys voter_id (wahl_id): gen treat_consol = (changed_wl==1 & (wl_added ==
>  0 & wl_dropped_lag[_n-1] == 0) )

.                         lab var treat_consol "Treated: New PP active before and old PP still act
> ive"

.                         
.                         // treat_no_consol : = if new PP previously inactive OR previous PP is i
> nactive now 
.                         bys voter_id (wahl_id): gen treat_no_consol = (changed_wl==1 & (wl_added
>  == 1 | wl_dropped_lag[_n-1] == 1))

.                         lab var treat_no_consol "Treated: New PP prev. inactive or previous PP n
> ow inactive"

.         
.                         assert treat_simple == treat_consol + treat_no_consol

.                         
.                         // How often did a PP reassignment coincide with a CHANGE IN PRECINCT SI
> ZE ?
.                         * sb_size_change := indicator if precinct size changed
.                         *       Note: precinct SIZE can change WITHOUT a PP reassignment and (PP
>  reassignment does not imply size change)
.                         cap drop tmp*

.                         bys sb_old wahl_id (voter_id): gen tmp_size=_N                  

.                         bys voter_id (wahl_id): gen sb_size_change = ((tmp_size!=tmp_size[_n-1]&
> _n>1))

.                         lab var sb_size_change "Precint SIZE changed"

.                         drop tmp*

. 
.                         
.                 *>>>>>>> DROP 2009 data <<<<<<<<<*
.                 drop if wahl_id == 0
(150,779 observations deleted)

.                 *>>>>>>> DROP 2009 data <<<<<<<<<*
. 
. ** Finalize dataset 
.         
.         // Encode polling place ID (wl_id) 
.         encode wl_id, gen(tmp1)

.         drop wl_id

.         rename tmp1 wl_id

.         
.  * save: address-level panel
.         sort voter_id wahl_id

.         compress
  variable changed_wl was float now byte
  variable treat_simple was float now byte
  variable street_increased was float now byte
  variable street_decreased was float now byte
  variable treat_consol was float now byte
  variable treat_no_consol was float now byte
  variable sb_size_change was float now byte
  variable wl_id was long now int
  (27,743,336 bytes saved)

.         save "$newdata/estimation_prep_ltw18_voter.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8_voter.dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8_voter.dta saved

. 
end of do-file
Running: 08_finalize_precinct_panel_ltw18.do

. /*
> Input:  
>         > estimation_prep_ltw18_voter [prepared voter-address panel] 
>         > tmp/migration_precincts.dta [prepared migration data (precinct level)]
>         > tmp/ltw18_sb_area.dta           [prepared precinct area (precinct level)]
>         > rawdata/RWI/02_data/final/election_rwi_red_sb_final [precinct-level rents by RWI]
>         
> Output: 
>         > newdata/estimation_prep_ltw18 [final precinct-level panel]
>         > arc_anly/arc_input/treated_precincts.txt [treated precincts for GIS processing]
> 
> Main tasks:             
>         > Collapse to precinct-level and compute relevant variables
>         > Generate relative time and sample definition for event study
> 
> */
. 
. 
. /*------ PRECINCT LEVEL ----------*/
. 
. * PULL: prepped address-level panel
. use "$newdata/estimation_prep_ltw18_voter.dta", clear   

. 
. ********************************************************************************
.         // Collapse to precinct level & gen relevant variables //
. ********************************************************************************
. **** COLLAPSE to election x precinct level      
.                 gcollapse  (mean) waehler* wahlber* ungueltige_stimmen ew_* wb_* avg_dur hh_*  /
> // 
>                                                                 anz* *street_dist* *creased *tre
> at* shr*  ///
>                                                                 wl_school* sb_size_change, ///
>                                                                         by(wahl wahl_type wahl_i
> d jahr sb_new stadtbez) labelformat(#sourcelabel#) fast                                         
>                 

. 
.         format  shr_* %9.4f

.         xtset sb_new wahl_id

Panel variable: sb_new (strongly balanced)
 Time variable: wahl_id, 1 to 8
         Delta: 1 unit

. 
.         
. **** MERGES 
. 
.         * Merge with migration data (across and within precincts)
.                 merge 1:1 sb_new wahl_id using "$tmp/migration_precincts.dta", assert(3 2) keep(
> 3) nogen
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                             4,944  
    -----------------------------------------

.         
.         * MERGE precinct area (SE-18)                                                           
.                 merge m:1 sb_new using "$tmp/ltw18_sb_area.dta", assert(3) nogen

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                             4,944  
    -----------------------------------------

.                 
.         * MERGE avg. rental prices (RWI) (precinct level)
.                 merge m:1 jahr sb_new using "$rawdata/RWI/02_data/final/election_rwi_red_sb_fina
> l", assert(3) keepusing(mpreis_flats_rent) nogen 
(variable jahr was int, now float to accommodate using data's values)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                             4,944  
    -----------------------------------------

. 
.         * MERGE with district level outcomes (STADTbezirk)
.                 merge m:1 stadtbez wahl using  "$tmp/stadtbez_postalcomp_partyoutc.dta", assert(
> 3) nogen
(variable stadtbez was byte, now float to accommodate using data's values)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                             4,944  
    -----------------------------------------

.                 
. **** Gen turnout variables (Outcomes)
.         * Turnourt Urne
.         gen     turnout_urne = (waehler_gesamt-waehler_mit_wahlschein)/wahlber_gesamt

.         lab var turnout_urne "Turnout at polling station / eligible pop)"

.         
.         * Turnout Postal requested
.         gen     turnout_pos_req =  wahlber_mit_wahlschein / wahlber_gesamt

.         lab var turnout_pos_req "Turnout eligible ppl with Wahlschein / eligible pop"

.         
.         * Turnout Overall
.         gen     turnout_tot_req = turnout_urne + turnout_pos_req

.         lab var turnout_tot_req "Total turnout, NOT corrected for postal compliance"

.         
. 
. **** gen/adjust Variables
. 
.  * gen log 
.         assert street_dist >0

.         gen ln_street_dist =ln(street_dist)

.         lab var ln_street_dist          "Log walking distance"

.         
.         assert ew_ges >0

.         gen ln_ew_ges =ln(ew_ges)

.         lab var ln_ew_ges               "Log number of residents"

.  
.  * norm. migration by size of population 
.         foreach v in withmig outmig inmig {
  2.                 gen     `v'_pop = `v'/ew_ges
  3.         }

.         lab var withmig_pop "\% within migration"

.         lab var outmig_pop  "\% Outmigration"

.         lab var inmig_pop  "\% Inmigration"

. 
.         
.  * gen ew_dtmihi := Germans with migration background
.         //      note:   ew_mihi: including non-EU foreigners (ew_ausl_else), 
.         //                                      EU foreigners (ew_ausl_eu), and Germans with 
.         //                                      a migration background (Deutsche mit MiHi).
.         //                      ew_dt: ethnic Germans without a migration background 
.         //                               and Germans with a migration background (Deutsche mit M
> iHi), combining both 
.         //                              native-born Germans and those of German citizenship with
>  migrant origins.
.         
.         gen ew_ausl = ew_ausl_eu + ew_ausl_else

.         
.         gen ew_dtmihi = ew_mihi - ew_ausl

.         
.         gen ew_biodt = ew_dt - ew_dtmihi                        // share of biodt + dtmihi + aus
> l = total

. 
.         gen wb_anteil = wahlber_gesamt/ew_ges   // share of electorate

.         
. 
.  * gen binary treatment dummies (parttreat_simple, fulltreat_simple)
.         // treated if > 0 (at least part of precinct treated)
.         foreach v of varlist treat_* {
  2.                 gen part`v' = (`v' >0)
  3.                 lab var part`v' "Binary treatment of `v' (treat > 0)"
  4.                 cap drop parttreat*dist
  5.          }

.         // treated if = 1 (WHOLE precinct treated)
.         foreach v of varlist treat_* {
  2.                 gen full`v' = (`v' == 1)
  3.                 lab var full`v' "Binary treatment of `v' (treat = 1)"
  4.                 cap drop fulltreat*dist
  5.          }

.          
. *** Outcomes
.         // share of mail-in votes in total votes
.         gen     share_mail = 100*turnout_pos_req/turnout_tot_req

.         lab var share_mail      "Share of Postal votes in total votes"  

. 
.         
. * Rescale Covariates to Percentages
.         foreach v of varlist wb_* ew_* hh_* *mig_pop {
  2.          if inrange(`v',0,1) {
  3.                 replace `v' = 100*`v'
  4.          }
  5.         }
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(2,472 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)
(4,797 real changes made)
(4,944 real changes made)
(4,944 real changes made)

.         
.         
.  * (Re-)label Variables for Table outputs
.         lab var del_street_dist         "Avg. change in walking distance (km)"

.         lab var street_increased "Share HH, where RA increased dist"

.         lab var street_decreased "Share HH, where RA decreased dist" 

.         lab var ew_ges          "Number of residents"

.         lab var ln_ew_ges       "Log number of residents"

.         lab var ew_biodt        "\% native German residents"

.         lab var ew_mihi         "\% migrant residents (MiHi+foreigners)"

.         lab var ew_dtmihi       "\% non-native German residents"

.         lab var ew_ausl         "\% foreign residents"

.         lab var ew_ausl_eu      "\% EU foreigners"

.         lab var ew_ausl_else "\% non-EU foreigners"

.         lab var ew_dt           "\% German residents"

.         lab var ew_ledig        "\% single residents"

.         lab var ew_married      "\% married residents"

.         
.         lab var wahlber_gesamt "Number of eligible voters"

.         lab var wb_anteil       "\% inhabitants eligible to vote"

.         lab var wb_dt           "\% Germans in the electorate"

.         lab var wb_ausl         "\% EU-foreigners in the electorate"

.         lab var wb_18t24        "\% electorate aged 18-24"

.         lab var wb_25t34        "\% electorate aged 25-34"

.         lab var wb_35t44        "\% electorate aged 35-44"

.         lab var wb_45t59        "\% electorate aged 45-59"

.         lab var wb_60plus       "\% electorate aged 60+"

.         
.         lab var avg_dur         "Average duration of residence"

.         lab var hh_kids         "\% households with children"

.         lab var hh_sgl          "\% single-person households"

.         
.         lab var area_sb_ltw18           "Area in qkm"

.         lab var mpreis_flats_rent       "Average quoted rent per sqm"

.         
.         lab var turnout_urne    "Polling place turnout"

.         lab var turnout_tot_req "Overall turnout (requested)"

.         lab var turnout_pos_req "Mail-in turnout (requested)"

.         
. * Gen absolute values of covariates in thousands
.         cap drop abs_*

.         foreach v of varlist ew_*{
  2.          if inrange(`v',0,100) {
  3.                 gen abs_`v' = ew_ges * (`v'/100) / 1000
  4.                 local lab : var lab `v'
  5.                 local labnew = subinstr("`lab'","\%", "Number of",.)
  6.                 local labnew "`labnew' (thsd)"
  7.                 lab var abs_`v' "`labnew'"
  8.          }
  9.         } 

.         foreach v of varlist wb_*{
  2.          if inrange(`v',0,100) {
  3.                 gen abs_`v' = wahlber_gesamt * (`v'/100) / 1000
  4.                 local lab : var lab `v'
  5.                 local labnew = subinstr("`lab'","\%", "Number of",.)
  6.                 local labnew "`labnew' (thsd)"
  7.                 lab var abs_`v' "`labnew'"
  8.          }
  9.         }       

.         gen             abs_ew_ges = ew_ges/1000

.         lab var         abs_ew_ges "Number of residents (thsd)"

.         
.         
. 
. 
. ********************************************************************************
.         // Generate relative time and sample definition for event study //
. ********************************************************************************
. 
.         * Lab vars for output
.         lab var turnout_urne            "Effect on polling place turnout"

.         lab var turnout_pos_req         "Effect on mail-in turnout"

.         lab var turnout_tot_req         "Effect on total turnout"

.         
. 
.         * rescale turnout       [0-100]
.         foreach v of varlist turnout* {
  2.                 assert inrange(`v',0,1)
  3.                 replace `v' = `v'* 100
  4.         }               
(4,944 real changes made)
(4,944 real changes made)
(4,944 real changes made)

.         
.         
.         * GEN fulltottreat100= Total nbr. of times a precinct is treated (reassigned=100%)
.         bys sb_new: egen fulltottreat100 = total(fulltreat_simple)      

.         lab var fulltottreat100 "Total treat_simple==1 by precinct"

.         
.         * GEn treat50_simple = Binary indicator for treat_simple >0.5
.         gen treat50_simple = (treat_simple >=.5)

.         lab var treat50_simple "Binary treatment (treat_simple >.5)"

.         
.         * Gen  fulltotreat50= Total nbr. of times a precinct is treated (>50% reassigned)
.         bys sb_new: egen fulltottreat50 = total(treat50_simple) 

.         lab var fulltottreat50 "Total treat_simple> .5 by precinct"

. 
. 
. ***** DEFINITION 1: Event= first time precinct is FULLY treated (treat_simple=1)        
.         cap drop tmp*

. 
.  * Gen relevant indicators      
.         // gen Ei = unit-specific date of treatment (never-treated = missing)
.         gen tmp_wahl_id = (-1)*wahl_id

.         bys sb_new (fulltreat_simple tmp_wahl_id): gen Ei = wahl_id[_N] if fulltottreat100>0 // 
> wahl_id where first FULL-treatment (treat_simple==1)
(2,704 missing values generated)

.         lab var Ei "date of treatment,treat=100% reassigned, NT=."

.         lab val Ei wahl_id

.         
.         // gen K = == "relative time", i.e. the number periods since treated (never-treated = mi
> ssing)
.         cap drop K

.         gen K = wahl_id- Ei     
(2,704 missing values generated)

.         lab var K "rel. time, treat=100% reassigned, NT=."

.         
.         // gen D treatment indicator (=1 post treatmeant, never-treated = 0)
.         cap drop D

.         gen D = K>=0 & Ei!=. 

.         lab var D "post-treatment dummy, treat=100% reassigned, NT=0"

.         
.         
.         // gen cleanctr = CONTROL has ZERO reassgs (precinct-level var)
.         cap drop tmp*

.         bys sb_new: egen tmp=total(treat_simple>0)

.         gen     cleanctr= (tmp==0)

.         replace cleanctr=1 if !missing(Ei) 
(2,240 real changes made)

.         lab var cleanctr "IDs treat=100% & CTRL w/ ZERO reassgn. throughout"

.         *tab Ei if cleanctr==1 & wahl_id==1, mis        
.         
.         
.         // gen never_treated := id precincts that are never-treated (=control precincts)
.         gen T = (Ei!=.) 

.         recode T (0=1)(1=0), gen(NT)
(4944 differences between T and NT)

.         lab var T  "treated units (Ei!=.)"

.         lab var NT "never treated unit (Ei=.)"

.         
.         * GEN sb_const_size: (precinct-level) ids CTRL and TREATED precincts w/o size changes in
>  t=0
.         gen     sb_const_size= (K==0 & sb_size_change==0)

.         replace sb_const_size=1 if missing(Ei)                  // all CTR precincts are include
> d
(2,704 real changes made)

.         assert !missing(sb_const_size)

.         bys sb_new (sb_const_size): replace sb_const_size=sb_const_size[_N]     
(378 real changes made)

. 
.  * Create (optional) sample restrictions
.         cap drop tmp*

.         
.         // smpl_trim: drop observations after SECOND treatment kicks in
.         cap drop        smpl_trim

.         gen             smpl_trim = 1

.         gen tmp_other_treats = (fulltreat_simple > 0 & K != 0)          // identify second treat
> ments after t0 ONLY 100%

.         bys sb_new (wahl_id): replace smpl_trim = 0 if (tmp_other_treats == 1 | smpl_trim[_n-1] 
> ==0) // set missing after second treatment kicks in     
(278 real changes made)

.         lab var smpl_trim "Obs after 2. treatment dropped, treat=100% reassigned"

.         
.         
.         // smpl_bal: balanced panel around t in (-4,2)
.         // -> includes FE-17, SE-18: 208 treated units
.         cap drop smpl_bal

.         cap drop help*

.         bys sb_new: gen help = (K==-4 | K==2)

.         bys sb_new: egen help2 = total(help)

.         gen smpl_bal = (missing(Ei) | help2 == 2)

.         lab var smpl_bal "=1 if NT or balanced in t(-4,2), treat=100%"

.         tab K if smpl_bal==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -5 |         35        2.10        2.10
         -4 |        208       12.50       14.60
         -3 |        208       12.50       27.10
         -2 |        208       12.50       39.60
         -1 |        208       12.50       52.10
          0 |        208       12.50       64.60
          1 |        208       12.50       77.10
          2 |        208       12.50       89.60
          3 |        173       10.40      100.00
------------+-----------------------------------
      Total |      1,664      100.00

.         drop help*

.         
.         
.         // smpl_bal17: balanced panel around FE-17 in (-4,2) [173 treated units]
.         gen smpl_bal17=smpl_bal 

.         replace smpl_bal17=0 if Ei !=5 & !missing(Ei)
(280 real changes made)

.         lab var smpl_bal17 "=1 if NT or balanced around FE-17, treat=100%"

.         tab K if smpl_bal17==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -4 |        173       12.50       12.50
         -3 |        173       12.50       25.00
         -2 |        173       12.50       37.50
         -1 |        173       12.50       50.00
          0 |        173       12.50       62.50
          1 |        173       12.50       75.00
          2 |        173       12.50       87.50
          3 |        173       12.50      100.00
------------+-----------------------------------
      Total |      1,384      100.00

. 
.         // smpl_bal_tp1: balanced panel around t in (-4,1) WITHOUT smpl_trim
.         //      -> includes FE-17, SE-18, EU-19: 220 treated units
.         cap drop help*

.         bys sb_new: gen help = (K==-4 | K==1)

.         bys sb_new: egen help2 = total(help)

.         gen     smpl_bal_tp1 = (missing(Ei) | help2 == 2)

.         lab var smpl_bal_tp1 "=1 if NT or balanced in t(-4,1), treat=100%"

.         tab K if smpl_bal_tp1==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -6 |         12        0.68        0.68
         -5 |         47        2.67        3.35
         -4 |        220       12.50       15.85
         -3 |        220       12.50       28.35
         -2 |        220       12.50       40.85
         -1 |        220       12.50       53.35
          0 |        220       12.50       65.85
          1 |        220       12.50       78.35
          2 |        208       11.82       90.17
          3 |        173        9.83      100.00
------------+-----------------------------------
      Total |      1,760      100.00

.         drop help*      

.         
.         // smpl_bal_tm2: balanced panel around t in (-2,2) WITHOUT smpl_trim
.         //      -> includes ME-14, FE-17, SE-18: 218 treated units
.         cap drop help*

.         bys sb_new: gen help = (K==-2 | K==2)

.         bys sb_new: egen help2 = total(help)

.         gen     smpl_bal_tm2 = (missing(Ei) | help2 == 2)

.         lab var smpl_bal_tm2 "=1 if NT or balanced in t(-2,2), treat=100%"

.         tab K if smpl_bal_tm2==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -5 |         35        2.01        2.01
         -4 |        208       11.93       13.93
         -3 |        208       11.93       25.86
         -2 |        218       12.50       38.36
         -1 |        218       12.50       50.86
          0 |        218       12.50       63.36
          1 |        218       12.50       75.86
          2 |        218       12.50       88.36
          3 |        183       10.49       98.85
          4 |         10        0.57       99.43
          5 |         10        0.57      100.00
------------+-----------------------------------
      Total |      1,744      100.00

.         drop help*      

.         
.         // smpl_bal_tpm: balanced panel around t in (-2,1) WITHOUT smpl_trim
.         //      -> includes ME-14m FE-17, SE-18, EU-19: 230 treated units
.         cap drop help*

.         bys sb_new: gen help = (K==-2 | K==1)

.         bys sb_new: egen help2 = total(help)

.         gen     smpl_bal_tpm = (missing(Ei) | help2 == 2)

.         lab var smpl_bal_tpm "=1 if NT or balanced in t(-2,1), treat=100%"

.         tab K if smpl_bal_tpm==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -6 |         12        0.65        0.65
         -5 |         47        2.55        3.21
         -4 |        220       11.96       15.16
         -3 |        220       11.96       27.12
         -2 |        230       12.50       39.62
         -1 |        230       12.50       52.12
          0 |        230       12.50       64.62
          1 |        230       12.50       77.12
          2 |        218       11.85       88.97
          3 |        183        9.95       98.91
          4 |         10        0.54       99.46
          5 |         10        0.54      100.00
------------+-----------------------------------
      Total |      1,840      100.00

.         drop help*      

.         
.         // smpl_bal_tp0: balanced panel around t in (-4,0) WITHOUT smpl_trim
.         //      -> includes ME-14m FE-17, SE-18, EU-19: 230 treated units
.         cap drop help*

.         bys sb_new: gen help = (K==-2 | K==0)

.         bys sb_new: egen help2 = total(help)

.         gen     smpl_bal_tp0 = (missing(Ei) | help2 == 2)

.         lab var smpl_bal_tp0 "=1 if NT or balanced in t(-4,0), treat=100%"

.         tab K if smpl_bal_tp0==1

 rel. time, |
 treat=100% |
reassigned, |
       NT=. |      Freq.     Percent        Cum.
------------+-----------------------------------
         -7 |         40        1.85        1.85
         -6 |         52        2.41        4.26
         -5 |         87        4.03        8.29
         -4 |        260       12.04       20.32
         -3 |        260       12.04       32.36
         -2 |        270       12.50       44.86
         -1 |        270       12.50       57.36
          0 |        270       12.50       69.86
          1 |        230       10.65       80.51
          2 |        218       10.09       90.60
          3 |        183        8.47       99.07
          4 |         10        0.46       99.54
          5 |         10        0.46      100.00
------------+-----------------------------------
      Total |      2,160      100.00

.         drop help*      

.         
.         
.         // smpl_trim_dist: only precincts w/ dist. increases based + smpl_trim
.         cap drop dincreas

.         gen      dincreas = del_street_dist>0 if K==0 // id precinct where distance increased
(4,664 missing values generated)

.         bys sb_new (dincreas): replace dincreas=dincreas[1]
(1960 real changes made)

.         replace  dincreas = 1 if Ei==.
(2,704 real changes made)

.         lab var dincreas "id preincts with dist increase in K=0 and NT"

.         
.         cap drop ddecreas

.         gen      ddecreas = del_street_dist<0 if K==0 // id precinct where distance increased
(4,664 missing values generated)

.         bys sb_new (ddecreas): replace ddecreas=ddecreas[1]
(1960 real changes made)

.         replace  ddecreas = 1 if Ei==.
(2,704 real changes made)

.         lab var ddecreas "id precincts with dist decrease in K=0 and NT"        

. 
.         gen     smpl_trim_dist = (smpl_trim==1&dincreas==1)

.         lab var smpl_trim_dist "=1 if NT or dist increase, treat=100%, 2. dropped"

.         clonevar smpl_trim_dist_up=smpl_trim_dist

.         
.         gen     smpl_trim_dist_dwn = (smpl_trim==1&ddecreas==1)

.         lab var smpl_trim_dist_dwn "=1 if NT or dist increase, treat=100%, 2. dropped"  

.         
. ***** DEFINITION 2: Event= first time precinct is >50% reassigned (treat_simple>.5)     
.         cap drop tmp*

.         
. * Gen relevant indicators       
.         // gen Ei50 = unit-specific date of treatment (never-treated = missing)
.         gen tmp_wahl_id = (-1)*wahl_id

.         bys sb_new (treat50_simple tmp_wahl_id): gen Ei50 = wahl_id[_N] if fulltottreat50>0 // w
> ahl_id where first FULL-treatment (treat_simple==1)
(1,968 missing values generated)

.         lab var Ei50 "date of treatment,treat=50% reassigned, NT=."

.         lab val Ei50 wahl_id

.         
.         // gen K = == "relative time", i.e. the number periods since treated (never-treated = mi
> ssing)
.         cap drop K50

.         gen K50 = wahl_id- Ei50 
(1,968 missing values generated)

.         lab var K50 "rel. time, treat=50% reassigned, NT=."

.         
.         // gen D treatment indicator (=1 post treatmeant, never-treated = 0)
.         cap drop D50

.         gen D50 = K50>=0 & Ei50!=. 

.         lab var D50 "post-treatment dummy, treat=50% reassigned, NT=0"

.         
.         // gen cleanctr50 = CONTROL has ZERO reassgs (precinct-level var)
.         cap drop tmp*

.         bys sb_new: egen tmp=total(treat_simple>0)

.         gen     cleanctr50= (tmp==0)

.         replace cleanctr50=1 if !missing(Ei50) 
(2,976 real changes made)

.         lab var cleanctr50 "IDs treat=50% & CTRL w/ ZERO reassgn. throughout"

.         *tab Ei if cleanctr==1 & wahl_id==1, mis        
. 
.  * Define (optional) sample restrictions
.         cap drop tmp*

.         
.         // smpl_trim50: drop observations after SECOND treatment (>50%) kicks in
.         cap drop        smpl_trim50

.         gen             smpl_trim50 = 1

.         gen tmp_other_treats = (treat50_simple > 0 & K50 != 0)          // identify second treat
> ments after t0

.         bys sb_new (wahl_id): replace smpl_trim50 = 0 if (tmp_other_treats == 1 | smpl_trim50[_n
> -1] ==0) // set missing after second treatment kicks in 
(417 real changes made)

.         lab var smpl_trim50 "Obs after 2. treatment dropped, treat=50% reassigned"

.         
.         
. ***** DEFINITION 3: Event= LARGEST Reassignment (treat_simple>0)        
.         cap drop tmp*

.         
. * Gen relevant indicators       
.         // gen Ei_max = unit-specific date of treatment (never-treated = missing)
.         cap drop Ei_max

.         gen tmp_wahl_id = (-1)*wahl_id

.         bys sb_new: egen tmp_max=max(treat_simple)

.         bys sb_new (treat_simple tmp_wahl_id): gen Ei_max = wahl_id[_N] if tmp_max>0 // wahl_id 
> where greatest shock (treat_simple>0), (first if more than one election)
(840 missing values generated)

.         lab var Ei_max "date of treatment,treat=max(treat_simple) reassigned, NT=."

.         
.         // gen K = == "relative time", i.e. the number periods since treated (never-treated = mi
> ssing)
.         cap drop K_max

.         gen K_max = wahl_id- Ei_max     
(840 missing values generated)

.         lab var K_max "rel. time, treat=max(treat_simple) reassigned, NT=."

.         
.         // gen D treatment indicator (=1 post treatmeant, never-treated = 0)
.         cap drop D_max

.         gen D_max = K_max>=0 & Ei_max!=. 

.         lab var D_max "post-treatment dummy, treat=max(treat_simple) reassigned, NT=0"

. 
.  * Define (optional) sample restrictions
.         cap drop tmp*

.         
.         // smpl_trim_max: drop observations after SECOND treatment (>50%) kicks in
.         cap drop        smpl_trim_max

.         gen             smpl_trim_max = 1

.         gen tmp_other_treats = (treat_simple > 0 & K_max > 0)           // NOTE: here I take ANY
>  positive treatment after K=0

.         bys sb_new (wahl_id): replace smpl_trim_max = 0 if (tmp_other_treats == 1 | smpl_trim_ma
> x[_n-1] ==0) // set missing after second treatment kicks in     
(505 real changes made)

.         lab var smpl_trim_max "Obs after 2. treatment dropped, treat=max(treat_simple) reassigne
> d"      

.         
.         cap drop tmp*

. * save
.         compress
  variable jahr was float now int
  variable stadtbez was float now byte
  variable sbez_anz_tpiraten was float now int
  variable sbez_anz_upiraten was float now int
  variable sbez_anz_ppiraten was float now int
  variable sbez_anz_tnpd was float now int
  variable sbez_anz_unpd was float now int
  variable sbez_anz_pnpd was float now byte
  variable sbez_anz_trep was float now int
  variable sbez_anz_urep was float now int
  variable sbez_anz_prep was float now int
  variable sbez_anz_tbuendnis21_rrp was float now byte
  variable sbez_anz_ubuendnis21_rrp was float now byte
  variable sbez_anz_pbuendnis21_rrp was float now byte
  variable sbez_anz_tbp was float now int
  variable sbez_anz_ubp was float now int
  variable sbez_anz_pbp was float now int
  variable sbez_anz_ttierschutzpartei was float now int
  variable sbez_anz_utierschutzpartei was float now int
  variable sbez_anz_ptierschutzpartei was float now int
  variable sbez_anz_tdievioletten was float now byte
  variable sbez_anz_udievioletten was float now byte
  variable sbez_anz_pdievioletten was float now byte
  variable sbez_anz_tbueso was float now byte
  variable sbez_anz_ubueso was float now byte
  variable sbez_anz_pbueso was float now byte
  variable sbez_anz_tmlpd was float now byte
  variable sbez_anz_umlpd was float now byte
  variable sbez_anz_pmlpd was float now byte
  variable sbez_anz_tprodeutschland was float now byte
  variable sbez_anz_uprodeutschland was float now byte
  variable sbez_anz_pprodeutschland was float now byte
  variable sbez_anz_tdiefrauen was float now byte
  variable sbez_anz_udiefrauen was float now byte
  variable sbez_anz_pdiefrauen was float now byte
  variable sbez_anz_tparteidervernunft was float now byte
  variable sbez_anz_uparteidervernunft was float now byte
  variable sbez_anz_pparteidervernunft was float now byte
  variable sbez_anz_tbge was float now int
  variable sbez_anz_ubge was float now byte
  variable sbez_anz_pbge was float now byte
  variable sbez_anz_tdib was float now int
  variable sbez_anz_udib was float now byte
  variable sbez_anz_pdib was float now byte
  variable sbez_anz_tdkp was float now byte
  variable sbez_anz_udkp was float now byte
  variable sbez_anz_pdkp was float now byte
  variable sbez_anz_tdm was float now byte
  variable sbez_anz_udm was float now byte
  variable sbez_anz_pdm was float now byte
  variable sbez_anz_udiepartei was float now int
  variable sbez_anz_pdiepartei was float now int
  variable sbez_anz_tgesundheitsforschung was float now byte
  variable sbez_anz_ugesundheitsforschung was float now byte
  variable sbez_anz_pgesundheitsforschung was float now byte
  variable sbez_anz_tvpartei was float now int
  variable sbez_anz_uvpartei was float now byte
  variable sbez_anz_pvpartei was float now byte
  variable sbez_anz_tfamilie was float now byte
  variable sbez_anz_ufamilie was float now byte
  variable sbez_anz_pfamilie was float now byte
  variable sbez_anz_tpbc was float now byte
  variable sbez_anz_upbc was float now byte
  variable sbez_anz_ppbc was float now byte
  variable sbez_anz_tvolksabstimmung was float now byte
  variable sbez_anz_uvolksabstimmung was float now byte
  variable sbez_anz_pvolksabstimmung was float now byte
  variable sbez_anz_tcm was float now byte
  variable sbez_anz_ucm was float now byte
  variable sbez_anz_pcm was float now byte
  variable sbez_anz_tauf was float now int
  variable sbez_anz_uauf was float now byte
  variable sbez_anz_pauf was float now byte
  variable sbez_anz_tpsg was float now byte
  variable sbez_anz_upsg was float now byte
  variable sbez_anz_ppsg was float now byte
  variable sbez_anz_tpronrw was float now byte
  variable sbez_anz_upronrw was float now byte
  variable sbez_anz_ppronrw was float now byte
  variable sbez_anz_tsgp was float now byte
  variable sbez_anz_usgp was float now byte
  variable sbez_anz_psgp was float now byte
  variable sbez_anz_ttierschutzhier was float now byte
  variable sbez_anz_utierschutzhier was float now byte
  variable sbez_anz_ptierschutzhier was float now byte
  variable sbez_anz_ttierschutzallianz was float now byte
  variable sbez_anz_utierschutzallianz was float now byte
  variable sbez_anz_ptierschutzallianz was float now byte
  variable sbez_anz_tbuendnisc was float now byte
  variable sbez_anz_ubuendnisc was float now byte
  variable sbez_anz_pbuendnisc was float now byte
  variable sbez_anz_tbig was float now int
  variable sbez_anz_ubig was float now int
  variable sbez_anz_pbig was float now byte
  variable sbez_anz_tdiedirekte was float now byte
  variable sbez_anz_udiedirekte was float now byte
  variable sbez_anz_pdiedirekte was float now byte
  variable sbez_anz_tdiem25 was float now int
  variable sbez_anz_udiem25 was float now int
  variable sbez_anz_pdiem25 was float now int
  variable sbez_anz_tiiiweg was float now byte
  variable sbez_anz_uiiiweg was float now byte
  variable sbez_anz_piiiweg was float now byte
  variable sbez_anz_tdiegrauen was float now byte
  variable sbez_anz_udiegrauen was float now byte
  variable sbez_anz_pdiegrauen was float now byte
  variable sbez_anz_tdierechte was float now byte
  variable sbez_anz_udierechte was float now byte
  variable sbez_anz_pdierechte was float now byte
  variable sbez_anz_tliebe was float now byte
  variable sbez_anz_uliebe was float now byte
  variable sbez_anz_pliebe was float now byte
  variable sbez_anz_tgrauepanther was float now byte
  variable sbez_anz_ugrauepanther was float now byte
  variable sbez_anz_pgrauepanther was float now byte
  variable sbez_anz_tlkr was float now byte
  variable sbez_anz_ulkr was float now byte
  variable sbez_anz_plkr was float now byte
  variable sbez_anz_tmenschlichewelt was float now byte
  variable sbez_anz_umenschlichewelt was float now byte
  variable sbez_anz_pmenschlichewelt was float now byte
  variable sbez_anz_tnl was float now byte
  variable sbez_anz_unl was float now byte
  variable sbez_anz_pnl was float now byte
  variable sbez_anz_toekolinx was float now byte
  variable sbez_anz_uoekolinx was float now byte
  variable sbez_anz_poekolinx was float now byte
  variable sbez_anz_tdiehumanisten was float now int
  variable sbez_anz_udiehumanisten was float now byte
  variable sbez_anz_pdiehumanisten was float now byte
  variable sbez_anz_tparteifuerdietiere was float now byte
  variable sbez_anz_uparteifuerdietiere was float now byte
  variable sbez_anz_pparteifuerdietiere was float now byte
  variable sbez_anz_uvolt was float now int
  variable sbez_anz_pvolt was float now int
  variable sbez_anz_tbia was float now int
  variable sbez_anz_ubia was float now int
  variable sbez_anz_pbia was float now int
  variable sbez_anz_tfair was float now int
  variable sbez_anz_ufair was float now int
  variable sbez_anz_pfair was float now int
  variable sbez_anz_umuenchenliste was float now int
  variable sbez_anz_tmut was float now int
  variable sbez_anz_umut was float now int
  variable sbez_anz_pmut was float now int
  variable sbez_anz_tzuba was float now int
  variable sbez_anz_uzuba was float now int
  variable sbez_anz_pzuba was float now int
  variable sbez_anz_tdiefreiheit was float now int
  variable sbez_anz_udiefreiheit was float now int
  variable sbez_anz_pdiefreiheit was float now int
  variable sbez_anz_phut was float now int
  variable waehler_ges_11 was float now int
  variable waehler_ohne_11 was float now int
  variable waehler_21 was float now int
  variable wahlber_mit_11 was float now int
  variable parttreat_simple was float now byte
  variable parttreat_consol was float now byte
  variable parttreat_no_consol was float now byte
  variable fulltreat_simple was float now byte
  variable fulltreat_consol was float now byte
  variable fulltreat_no_consol was float now byte
  variable fulltottreat100 was float now byte
  variable treat50_simple was float now byte
  variable fulltottreat50 was float now byte
  variable Ei was float now byte
  variable K was float now byte
  variable D was float now byte
  variable cleanctr was float now byte
  variable T was float now byte
  variable NT was float now byte
  variable sb_const_size was float now byte
  variable smpl_trim was float now byte
  variable smpl_bal was float now byte
  variable smpl_bal17 was float now byte
  variable smpl_bal_tp1 was float now byte
  variable smpl_bal_tm2 was float now byte
  variable smpl_bal_tpm was float now byte
  variable smpl_bal_tp0 was float now byte
  variable dincreas was float now byte
  variable ddecreas was float now byte
  variable smpl_trim_dist was float now byte
  variable smpl_trim_dist_up was float now byte
  variable smpl_trim_dist_dwn was float now byte
  variable Ei50 was float now byte
  variable K50 was float now byte
  variable D50 was float now byte
  variable cleanctr50 was float now byte
  variable smpl_trim50 was float now byte
  variable Ei_max was float now byte
  variable K_max was float now byte
  variable D_max was float now byte
  variable smpl_trim_max was float now byte
  (2,615,376 bytes saved)

.         save "$newdata/estimation_prep_ltw18.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8.dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8.dta saved

.         
.         
. ** EXPORT files to ArcGIS for mapping & processing
. 
.  * Export treated and never-treated precincts to build locally matched sample in ArcGIS
.         export delim sb_new T using "$arc_anly/arc_input/treated_precincts.txt" if wahl_id==1, r
> eplace
file //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/06_arc_analyze/arc_input/treated
> _precincts.txt saved

. 
end of do-file
Running: 09_finalize_district_panel.do

. /*
> Main input:     
>         > tmp/raw_stimmbez_full.dta [prepped struc indicators, precinct-lvl] 
>         > newdata/estimation_prep_ltw18_voter.dta [prepped voter panel, precinct-lvl] 
>         > tmp/stadtbez_postalcomp_partyoutc.dta [prepped postal party outcomes, district-lvl] 
>         > rawdata/RWI/02_data/final/election_rwi_red_sb_final.dta [quoted rents, precinct-lvl] 
> 
> Output: newdata/estimation_prep_ltw18_stadtbez.dta 
>                         [District level panel, ID: stadtbez x wahl_id]
>                         
> Main task:
>         > aggregate precinct-level controls to DISTRICT-level
>         > aggregate precinct-level treatment variables to DISTRICT-level
>         > Merge district-level party outcomes 
> 
> Note: only used in the estimation file: 03h
> 
> */
. 
. 
. * PULL: structural indicators (precinct-level)
. use "$tmp/raw_stimmbez_full.dta", clear

. 
.         * drop precinct and turnout
.         drop sb gebietsartschluessel stimmbezirksart wahlber* waehl* kow_sti* anz* unguel*

. 
.         * collapse to district level
.         gcollapse (sum) ew_* wb_* hh_* (mean) avg_dur, by(wahl stadtbez) labelformat(#sourcelabe
> l#) fast

. 
. * Convert structural indicators back to shares
.         foreach v of varlist ew_dt ew_ausl* ew_mihi ew_ledig ew_married hh_sgl hh_kids{
  2.                 replace `v' = `v' /ew_ges
  3.                 assert inrange(`v',0,1) if wahl != "BTW2009"
  4.         }
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)

. 
. * save
.         tempfile struktur_ind_stadtbez 

.         save `struktur_ind_stadtbez'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000001.tmp saved as .dta format

. 
. 
. * PULL: prepped address-level panel
. use "$newdata/estimation_prep_ltw18_voter.dta", clear   

. 
. frame copy default tmp, replace

. frame tmp {
.                 // collapse from address to precinct level
.                 gcollapse (mean) waehler_gesamt waehler_mit_wahlschein ungueltige_stimmen ///
>                         wahlber_gesamt wahlber_ohne_wahlschein wahlber_mit_wahlschein wahlber_ni
> cht_im_waehlerv, ///
>                         by(wahl wahl_type wahl_id jahr stadtbez sb_new) labelformat(#sourcelabel
> #) fast
. 
.                 // collapse from precinct to district level (sum over precinct)
.                 gcollapse (sum) waehler_gesamt waehler_mit_wahlschein ungueltige_stimmen ///
>                         wahlber_gesamt wahlber_ohne_wahlschein wahlber_mit_wahlschein wahlber_ni
> cht_im_waehlerv, ///
>                         by(wahl wahl_type wahl_id jahr stadtbez) labelformat(#sourcelabel#) fast
. 
. * save
.         tempfile votes_stadtbez 
.         save `votes_stadtbez'
file C:\Users\Alipour\AppData\Local\Temp\9\ST_77c8_000002.tmp saved as .dta format
. }

.         
.                 
.         * MERGE avg. quoted rents (precinct level)
.                 merge m:1 jahr sb_new using "$rawdata/RWI/02_data/final/election_rwi_red_sb_fina
> l", assert(3) keepusing(mpreis_flats_rent) nogen 
(variable jahr was int, now float to accommodate using data's values)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                         1,206,232  
    -----------------------------------------

.         
.         * Collapse treatment variables (reassignments, distance) to district level
.         gcollapse (mean) *street_dist* *treat* mpreis_*, ///
>                         by(wahl wahl_type wahl_id jahr stadtbez) labelformat(#sourcelabel#) fast

. 
.         * MERGE back aggr. votes
.         merge 1:1 wahl wahl_type wahl_id jahr stadtbez using `votes_stadtbez', assert(3) nogen
(label wahl_type already defined)
(label wahl_id already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                               200  
    -----------------------------------------

.         
.         * MERGE with district level outcomes (STADTbezirk)
.         merge m:1 stadtbez wahl using  "$tmp/stadtbez_postalcomp_partyoutc.dta", assert(3) nogen
(variable stadtbez was byte, now float to accommodate using data's values)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                               200  
    -----------------------------------------

.         format sbez_shr* %9.4f

. 
.         * MERGE covariates
.         merge 1:1 wahl stadtbez using `struktur_ind_stadtbez', assert(3) nogen

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                               200  
    -----------------------------------------

.                 
.                 
. * gen logs
.         assert ew_ges > 0

.         gen     ln_ew_ges = ln(ew_ges)

.         lab var ln_ew_ges       "Log number of residents"

.         
.         gen     ew_ausl = ew_ausl_eu + ew_ausl_else

.         lab var ew_ausl         "\% foreign residents"

.         gen     ew_dtmihi = ew_mihi - ew_ausl

.         lab var ew_dtmihi       "\% non-native German residents"

.         gen     ew_biodt = ew_dt - ew_dtmihi                    

.         lab var ew_biodt        "\% native German residents"

.         gen     wb_anteil = wahlber_gesamt/ew_ges       

.         lab var wb_anteil       "\% inhabitants eligible to vote"

. 
. 
. * Rescale Covariates to Percentages
.         foreach v of varlist wb_* ew_* hh_* {
  2.                  if inrange(`v',0,1) {
  3.                         replace `v' = 100*`v'
  4.                  }
  5.         }
(100 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)
(200 real changes made)

.         
.  * (Re-)label Variables
.         lab var ew_ges          "Number of residents"

.         lab var ln_ew_ges       "Log number of residents"

.         lab var ew_biodt        "\% native German residents"

.         lab var ew_mihi         "\% migrant residents (MiHi+foreigners)"

.         lab var ew_dtmihi       "\% non-native German residents"

.         lab var ew_ausl         "\% foreign residents"

.         lab var ew_ausl_eu      "\% EU foreigners"

.         lab var ew_ausl_else "\% non-EU foreigners"

.         lab var ew_dt           "\% German residents"

.         lab var ew_ledig        "\% single residents"

.         lab var ew_married      "\% married residents"

.         
.         lab var wahlber_gesamt "Number of eligible voters"

.         lab var wb_anteil       "\% inhabitants eligible to vote"

.         lab var wb_dt           "\% Germans in the electorate"

.         lab var wb_ausl         "\% EU-foreigners in the electorate"

.         lab var wb_18t24        "\% electorate aged 18-24"

.         lab var wb_25t34        "\% electorate aged 25-34"

.         lab var wb_35t44        "\% electorate aged 35-44"

.         lab var wb_45t59        "\% electorate aged 45-59"

.         lab var wb_60plus       "\% electorate aged 60+"

.         
.         lab var avg_dur         "Average duration of residence"

.         lab var hh_kids         "\% households with children"

.         lab var hh_sgl          "\% single-person households"

.         
.         lab var mpreis_flats_rent       "Average quoted rent per sqm"

.         
. * save District level panel
.         compress
  variable jahr was float now int
  variable stadtbez was float now byte
  variable sbez_anz_tpiraten was float now int
  variable sbez_anz_upiraten was float now int
  variable sbez_anz_ppiraten was float now int
  variable sbez_anz_tnpd was float now int
  variable sbez_anz_unpd was float now int
  variable sbez_anz_pnpd was float now byte
  variable sbez_anz_trep was float now int
  variable sbez_anz_urep was float now int
  variable sbez_anz_prep was float now int
  variable sbez_anz_tbuendnis21_rrp was float now byte
  variable sbez_anz_ubuendnis21_rrp was float now byte
  variable sbez_anz_pbuendnis21_rrp was float now byte
  variable sbez_anz_tbp was float now int
  variable sbez_anz_ubp was float now int
  variable sbez_anz_pbp was float now int
  variable sbez_anz_ttierschutzpartei was float now int
  variable sbez_anz_utierschutzpartei was float now int
  variable sbez_anz_ptierschutzpartei was float now int
  variable sbez_anz_tdievioletten was float now byte
  variable sbez_anz_udievioletten was float now byte
  variable sbez_anz_pdievioletten was float now byte
  variable sbez_anz_tbueso was float now byte
  variable sbez_anz_ubueso was float now byte
  variable sbez_anz_pbueso was float now byte
  variable sbez_anz_tmlpd was float now byte
  variable sbez_anz_umlpd was float now byte
  variable sbez_anz_pmlpd was float now byte
  variable sbez_anz_tprodeutschland was float now byte
  variable sbez_anz_uprodeutschland was float now byte
  variable sbez_anz_pprodeutschland was float now byte
  variable sbez_anz_tdiefrauen was float now byte
  variable sbez_anz_udiefrauen was float now byte
  variable sbez_anz_pdiefrauen was float now byte
  variable sbez_anz_tparteidervernunft was float now byte
  variable sbez_anz_uparteidervernunft was float now byte
  variable sbez_anz_pparteidervernunft was float now byte
  variable sbez_anz_tbge was float now int
  variable sbez_anz_ubge was float now byte
  variable sbez_anz_pbge was float now byte
  variable sbez_anz_tdib was float now int
  variable sbez_anz_udib was float now byte
  variable sbez_anz_pdib was float now byte
  variable sbez_anz_tdkp was float now byte
  variable sbez_anz_udkp was float now byte
  variable sbez_anz_pdkp was float now byte
  variable sbez_anz_tdm was float now byte
  variable sbez_anz_udm was float now byte
  variable sbez_anz_pdm was float now byte
  variable sbez_anz_udiepartei was float now int
  variable sbez_anz_pdiepartei was float now int
  variable sbez_anz_tgesundheitsforschung was float now byte
  variable sbez_anz_ugesundheitsforschung was float now byte
  variable sbez_anz_pgesundheitsforschung was float now byte
  variable sbez_anz_tvpartei was float now int
  variable sbez_anz_uvpartei was float now byte
  variable sbez_anz_pvpartei was float now byte
  variable sbez_anz_tfamilie was float now byte
  variable sbez_anz_ufamilie was float now byte
  variable sbez_anz_pfamilie was float now byte
  variable sbez_anz_tpbc was float now byte
  variable sbez_anz_upbc was float now byte
  variable sbez_anz_ppbc was float now byte
  variable sbez_anz_tvolksabstimmung was float now byte
  variable sbez_anz_uvolksabstimmung was float now byte
  variable sbez_anz_pvolksabstimmung was float now byte
  variable sbez_anz_tcm was float now byte
  variable sbez_anz_ucm was float now byte
  variable sbez_anz_pcm was float now byte
  variable sbez_anz_tauf was float now int
  variable sbez_anz_uauf was float now byte
  variable sbez_anz_pauf was float now byte
  variable sbez_anz_tpsg was float now byte
  variable sbez_anz_upsg was float now byte
  variable sbez_anz_ppsg was float now byte
  variable sbez_anz_tpronrw was float now byte
  variable sbez_anz_upronrw was float now byte
  variable sbez_anz_ppronrw was float now byte
  variable sbez_anz_tsgp was float now byte
  variable sbez_anz_usgp was float now byte
  variable sbez_anz_psgp was float now byte
  variable sbez_anz_ttierschutzhier was float now byte
  variable sbez_anz_utierschutzhier was float now byte
  variable sbez_anz_ptierschutzhier was float now byte
  variable sbez_anz_ttierschutzallianz was float now byte
  variable sbez_anz_utierschutzallianz was float now byte
  variable sbez_anz_ptierschutzallianz was float now byte
  variable sbez_anz_tbuendnisc was float now byte
  variable sbez_anz_ubuendnisc was float now byte
  variable sbez_anz_pbuendnisc was float now byte
  variable sbez_anz_tbig was float now int
  variable sbez_anz_ubig was float now int
  variable sbez_anz_pbig was float now byte
  variable sbez_anz_tdiedirekte was float now byte
  variable sbez_anz_udiedirekte was float now byte
  variable sbez_anz_pdiedirekte was float now byte
  variable sbez_anz_tdiem25 was float now int
  variable sbez_anz_udiem25 was float now int
  variable sbez_anz_pdiem25 was float now int
  variable sbez_anz_tiiiweg was float now byte
  variable sbez_anz_uiiiweg was float now byte
  variable sbez_anz_piiiweg was float now byte
  variable sbez_anz_tdiegrauen was float now byte
  variable sbez_anz_udiegrauen was float now byte
  variable sbez_anz_pdiegrauen was float now byte
  variable sbez_anz_tdierechte was float now byte
  variable sbez_anz_udierechte was float now byte
  variable sbez_anz_pdierechte was float now byte
  variable sbez_anz_tliebe was float now byte
  variable sbez_anz_uliebe was float now byte
  variable sbez_anz_pliebe was float now byte
  variable sbez_anz_tgrauepanther was float now byte
  variable sbez_anz_ugrauepanther was float now byte
  variable sbez_anz_pgrauepanther was float now byte
  variable sbez_anz_tlkr was float now byte
  variable sbez_anz_ulkr was float now byte
  variable sbez_anz_plkr was float now byte
  variable sbez_anz_tmenschlichewelt was float now byte
  variable sbez_anz_umenschlichewelt was float now byte
  variable sbez_anz_pmenschlichewelt was float now byte
  variable sbez_anz_tnl was float now byte
  variable sbez_anz_unl was float now byte
  variable sbez_anz_pnl was float now byte
  variable sbez_anz_toekolinx was float now byte
  variable sbez_anz_uoekolinx was float now byte
  variable sbez_anz_poekolinx was float now byte
  variable sbez_anz_tdiehumanisten was float now int
  variable sbez_anz_udiehumanisten was float now byte
  variable sbez_anz_pdiehumanisten was float now byte
  variable sbez_anz_tparteifuerdietiere was float now byte
  variable sbez_anz_uparteifuerdietiere was float now byte
  variable sbez_anz_pparteifuerdietiere was float now byte
  variable sbez_anz_uvolt was float now int
  variable sbez_anz_pvolt was float now int
  variable sbez_anz_tbia was float now int
  variable sbez_anz_ubia was float now int
  variable sbez_anz_pbia was float now int
  variable sbez_anz_tfair was float now int
  variable sbez_anz_ufair was float now int
  variable sbez_anz_pfair was float now int
  variable sbez_anz_umuenchenliste was float now int
  variable sbez_anz_tmut was float now int
  variable sbez_anz_umut was float now int
  variable sbez_anz_pmut was float now int
  variable sbez_anz_tzuba was float now int
  variable sbez_anz_uzuba was float now int
  variable sbez_anz_pzuba was float now int
  variable sbez_anz_tdiefreiheit was float now int
  variable sbez_anz_udiefreiheit was float now int
  variable sbez_anz_pdiefreiheit was float now int
  variable sbez_anz_phut was float now int
  variable waehler_ges_11 was float now int
  variable waehler_ohne_11 was float now int
  variable waehler_21 was float now int
  variable wahlber_mit_11 was float now int
  variable ew_ges was double now long
  (84,400 bytes saved)

.         isid stadtbez wahl_id

.         save "$newdata/estimation_prep_ltw18_stadtbez.dta", replace
(file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8_stadtbez.dta not found)
file
    //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/04_newdata/estimation_prep_ltw1
    > 8_stadtbez.dta saved

.         
.         
.         
.         
. 
end of do-file

.          
.         
.         /* erase auxiliary files from tmp folder */
.         local files : dir "$tmp/" files "*.dta"

.         foreach f of local files {
  2.                 erase "$tmp/`f'"
  3.         }

.         log close
      name:  <unnamed>
       log:  //vmpfs-int/ag-int$/05_Forschungsprojekte/voting/Replication/07_output/logs/2_build_d
> atasets.log
  log type:  text
 closed on:   3 Mar 2024, 12:18:49
--------------------------------------------------------------------------------------------------
